1 # 首先你得先知道bind 和 call 的用法
2 # bind和call都是修改原有对象所属的上下文,也就是this
3 # 区别是bind之后并不会调用函数,call是直接调用
4
5 # 拓展内置对象
6 # 内置对象不允许修改原型对象原有属性的,只能新增
7 # 例:拓展Array内置对象,新增求数组内所有偶数的和
8 var array = [5,4,3,8];
9 Array.prototype.getSum = function () {
10 var sum = 0;
11 for (var i = 0; i < this.length; i++) {
12 if (this[i] % 2 === 0) {
13 sum += this[i];
14 }
15 }
16 return sum;
17 }
18 array.getSum(); # 结果是14
19
20 # 继承
21 # 一、通过对象copy
22 var zs = {
23 name: '张三',
24 money: 10000000,
25 cars: ['玛莎拉蒂', '特斯拉'],
26 hourses: ['别墅', '大别墅'],
27 play: function () {
28 console.log('打高尔夫')
29 }
30 }
31 var zxs = {
32 name: '张小三'
33 }
34 function extend(parent, child) {
35 for (var key in parent) {
36 if (child[key]) {
37 continue;
38 }
39 child[key] = parent[key];
40 }
41 }
42 extend(zs, zxs);
43
44 # 二、原型继承
45 function Person () {
46 this.name = 'zs';
47 this.age = 18;
48 this.sex = '男';
49 }
50 function Student() {
51 this.score = 100;
52 }
53 Student.prototype = new Person(); # 无法配置构造函数参数
54 Student.prototype.constructor = Student;
55 var s1 = new Student() # 无法配置构造函数参数
56
57 # 三、借用构造函数
58 function Person (name, age, sex) {
59 this.name = name;
60 this.age = age;
61 this.sex = sex;
62 }
63 Person.prototype.sayHello = function () {
64 console.log(this.name);
65 }
66 function Student(name, age, sex) {
67 Person.call(this, name, age, sex); # 解决了构造传参问题
68 this.score = 100;
69 }
70 Student.prorotype = Person.prototype; # 解决了方法继承的问题
71 Student.prototype.constructor = Student;# 但是这个时候改变了Person构造函数的原型对象,这样导致constructor,是如果再有一个新类需要继承Person的话就会出现原型对象冲突问题
72
73 # 四、解决原型对象冲突问题
74 function Person (name, age, sex) {
75 this.name = name;
76 this.age = age;
77 this.sex = sex;
78 }
79 Person.prototype.sayHello = function () {
80 console.log(this.name);
81 }
82 function Student(name, age, sex) {
83 Person.call(this, name, age, sex);
84 this.score = 100;
85 }
86 Student.prorotype = new Person(); # 这样子就解决看原型对象冲突的问题了。
87 Student.prototype.constructor = Student; # 再如何修改原型对象都不会影响其他构造函数。