js 继承

  1. 云栖社区>
  2. 博客>
  3. 正文

js 继承

烟海之蓝 2019-08-17 11:01:25 浏览111
展开阅读全文

构造函数绑定

function Animal() {
    this.species = '动物';
}

function Cat(name,color){
    Animal.apply(this, arguments);
    this.name = name;
    this.color = color;
}
var cat1 = new Cat("大毛","黄色");
console.log((cat1.species)); // 动物

prototype模式

function Animal() {
    this.species = '动物';
}

function Cat(name,color){
    this.name = name;
    this.color = color;
}

Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;

var cat1 = new Cat("大毛","黄色");
console.log((cat1.species)); // 动物

直接继承prototype

function Animal() {}
Animal.prototype.species = '动物';

function Cat(name,color){
    this.name = name;
    this.color = color;
}

Cat.prototype = Animal.prototype;
Cat.prototype.constructor = Cat;

var cat1 = new Cat("大毛","黄色");
console.log((cat1.species)); // 动物

与前一种方法相比,这样做的优点是效率比较高(不用执行和建立Animal的实例了),比较省内存。缺点是 Cat.prototype和Animal.prototype现在指向了同一个对象,那么任何对Cat.prototype的修改,都会反映到Animal.prototype。

利用空对象作为中介 寄生组合继承

function Animal() {}
Animal.prototype.species = '动物';

function Cat(name,color){
    Animal.call(this) // 借用构造函数继承属性
    this.name = name;
    this.color = color;
}

var F = function () {};
F.prototype = Animal.prototype;

Cat.prototype = new F();
Cat.prototype.constructor = Cat;
alert(Animal.prototype.constructor); // Animal
var cat1 = new Cat("大毛","黄色");
console.log((cat1.species)); // 动物


function Extend(child, parent) { // 继承原型的副本
    //var F = function () {};
    //F.prototype = parent.prototype;
    //child.prototype = new F();
       child.prototype = Object.create(parent.prototype)
    child.prototype.constructor = child;
    child.uber= parent.prototype;
}
Extend(Cat, Animal);
var cat1 = new Cat("大毛","黄色");

console.log((cat1.species)); // 动物

网友评论

登录后评论
0/500
评论
烟海之蓝
+ 关注