构造函数:就是一个构造对象的函数
特点:
1.函数名首字母大写
2.指向实例化的对象(谁new-this指向谁


  1. <script>
  2. /* 构造函数:就是一个构造对象的函数
  3. 特点:
  4. 1.函数名首字母大写
  5. 2.指向实例化的对象(谁new-this指向谁
  6. */
  7. function Person(name,age){
  8. this._name =name;
  9. this._age =age;
  10. }
  11. /* 使用new关键字就可以实例化一个对象了 */
  12. var p =new Person("lss",18);
  13. var li = new Person("lisi",17);
  14. console.log(p)
  15. console.log(li)
  16. /*
  17. 构造函数(类) --学生 -一类事物的抽象
  18. 对象 --实际的对象 --类的示例
  19. */
  20. </script>

1-1. Array 构造函数

  1. *****
  2. <script>
  3. /* Array 构造函数--数组类 */
  4. /* 在数组的原型上定义了一个say,那么所有的实例都会拥有一个say */
  5. Array.prototype.say = function(){
  6. console.log("say")
  7. }
  8. var arr = new Array(1,2,3);
  9. arr.push(5);
  10. console.log(arr);
  11. arr.say();
  12. var res =[];
  13. res.say();
  14. </script>
  15. ******
  16. <script>
  17. Array.prototype.push=function(){
  18. console.log("失效了")
  19. }
  20. var arr =[];
  21. arr.push(4);
  22. console.log(arr)
  23. /* remove(value) */
  24. Array.prototype.remove =function(val){
  25. var index =this.indexOf(val);
  26. this.splice(index,1);
  27. return this;
  28. }
  29. var arr=[3,4,5,6];
  30. console.log(arr.remove(6));
  31. /* sum */
  32. Array.prototype.sum =function(){
  33. var s =0;
  34. for(var i=0;i<this.length;i++){
  35. s+=this[i];
  36. }
  37. return s
  38. }
  39. var test =[1,2,3];
  40. console.log(test.sum())
  41. </script>

可封装到一个js文件复用

  1. *****
  2. Array.prototype.sum =function(){
  3. var s =0;
  4. for(var i=0;i<this.length;i++){
  5. s+=this[i];
  6. }
  7. return s
  8. }
  9. Array.prototype.remove =function(val){
  10. var index =this.indexOf(val);
  11. this.splice(index,1);
  12. return this;
  13. }
  14. *****
  15. <!DOCTYPE html>
  16. <html lang="en">
  17. <head>
  18. <meta charset="UTF-8">
  19. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  20. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  21. <title>Document</title>
  22. <script src="array.js"></script>
  23. </head>
  24. <body>
  25. <script>
  26. var arr =[3,4,56];
  27. console.log(arr.sum());
  28. arr.remove(4);
  29. console.log(arr)
  30. </script>
  31. </body>
  32. </html>

1.构建函数必须通过new关键字才可以调用
2.this指向实例化的对象

  1. <script>
  2. /* 1.构建函数必须通过new关键字才可以调用 */
  3. /* 2.this指向实例化的对象 */
  4. function Student(name,age,skill){
  5. this.name = name;
  6. this.age = age;
  7. this.skill = skill;
  8. }
  9. Student.prototype.sayName =function(){
  10. console.log(this.name)
  11. }
  12. Student.prototype.saySkill =function(){
  13. console.log(this.skill)
  14. }
  15. var p = new Student("lisi",18,"web");
  16. console.log(p)
  17. p.sayName();
  18. p.saySkill();
  19. </script>