function Super(){ this.name = ‘man‘; this.arr = [1,2,3] } var a = new Super(); a.name = ‘woman‘; a.arr.push(4); console.log(a.name); // woman console.log(a.arr); // [1,2,3,4] var b = new Super(); console.log(b.name); // man console.log(b.arr); // [1,2,3]
在没有继承的情况下,new出来的实例深度复制了构造函数中的属性
function SuperClass(){ this.name = "women"; this.bra = ["a","b"]; } function SubClass(){ this.subname = "your sister"; } SubClass.prototype = new SuperClass(); var sub1 = new SubClass(); sub1.name = "man"; sub1.bra.push("c"); console.log(sub1.name);//man console.log(sub1.hasOwnProperty(‘name‘)) //true console.log(sub1.bra);//["a","b","c"] var sub2 = new SubClass(); console.log(sub2.hasOwnProperty(‘name‘)) //false console.log(sub2.name);//woman console.log(sub2.bra);//["a","b","c"]
证明了仅通过原型链继承的话,子类的实例共享子类的原型对象(也就是共享父类的实例,父类实例化了一次,也就是仅仅深拷贝了一次)
function SuperClass() { this.name = "women"; this.bra = ["a", "b"]; } function SubClass() { this.subname = "your sister"; //将SuperClass的作用域赋予当前构造函数,实现继承 SuperClass.call(this); } var sub1 = new SubClass(); sub1.bra.push("c"); console.log(sub1.bra);//["a","b","c"] var sub2 = new SubClass(); console.log(sub2.bra);//["a","b"]
function SuperClass() { this.name = "women"; this.bra = ["a", "b"]; } SuperClass.prototype.sayWhat = function(){ console.log("hello"); } function SubClass() { this.subname = "your sister"; SuperClass.call(this); } var sub1 = new SubClass(); console.log(sub1.sayWhat());//TypeError: undefined is not a function
而通过借用构造函数的方法来继承的话,每个子类的实例中都有了父类构造函数的属性(深拷贝),但要是方法在构造函数中的化,那就造成浪费内存,没有实现方法的服用,
而且仅通过这种方式实现继承的化,父类的原型中的方法继承不到;
function SuperClass() { this.name = "women"; this.bra = ["a", "b"]; } SuperClass.prototype.sayWhat = function(){ console.log("hello"); } function SubClass() { this.subname = "your sister"; SuperClass.call(this); //第二次调用SuperClass } SubClass.prototype = new SuperClass(); //第一次调用SuperClass var sub1 = new SubClass(); console.log(sub1.sayWhat());//hello
因此可以通过原型链 + 借用构造函数实现:每个子类的实例中都有了父类构造函数的属性(深拷贝,然后每个子类实例跟父构造函数拥有相同的属性,因此仅查找它自身,而不会 沿着原型链去查找,从而实现了改变自身不影响别人),而要复用的,一般是方法,就放在原型对象上。
时间: 2024-10-10 02:44:42