Javascript继承方法(三)

五,构造函数 call()方法继承

function superText(name) {
    this.name = 'jiang';
    this.age = 20;
    this.method = function () {
        console.log("it is worth.")
    }
superText.prototype.like="play";
}
function subText() {
    //构造函数继承了superText(并不能继承到superText的原型的属性和方法)
    superText.call(this);
}
var  s = new subText();
s.name = 'wang';
console.log(s.name+" "+ s.age);
s.method();
var  s1 = new subText();
console.log(s1.name+" "+ s1.age);
s1.method();
console.log(s.like);
////////////////////传递参数
function superTYpe(name) {
    this.name = name;
}
function grangsonText() {
    superTYpe.call(this,"jack");
}
var g = new grangsonText();
console.log(g.name);
运行结果:
wang 20
it is worth.
jiang 20
it is worth.
undefined
jack
  这种方法实质是调用了call的方法将this指向了superText的作用域,从而获得了其属性方法的继承,当我想要调用superText的原型属性时是undefined,说明此方法不能继承到它的原型属性和方法

六,寄生组合式继承

function inheritPrototype(subType,superType) {
    var prototype = Object(superType.prototype);
    prototype.constructor = subType;
    subType.prototype = prototype;
}
function SuperType(name) {
    this.name = name;
    this.color = ['red','green','black'];
}
SuperType.prototype.sayName = function () {
  console.log(this.name);
};
function SubType(name,age) {
    SuperType.call(this,name);

    this.age = age;
}
inheritPrototype(SubType,SuperType);
SubType.prototype.sayAge = function () {
    console.log(this.age);
};
var s = new SubType('tomjack',19);
s.sayName();
s.sayAge();
console.log(s.color);
运行结果:
tomjack
19
[ 'red', 'green', 'black' ]

inheritPrototype()函数接受两个参数:子类型的构造函数和超类型的构造函数。在函数内部第一步式创建一个超类型的原型副本
第二步为创建的副本添加constructor属性,从而弥补重写原型而失去默认的constructor属性,最后一步讲创建的副本赋值给子类型的原型。
特点 : 只调用了一次SuperType构造函数,高效,避免了在Subtype.prototype上创建了不必要的,多余的属性。

说明:此段代码摘抄至《JavaScript高级程序设计》这本书的讲原型部分

猜你喜欢

转载自blog.csdn.net/qq_37800534/article/details/78031032