Understanding of js prototype inheritance

//原型继承
function SuperType(){
    this.property = true ;
}
console.log("SuperType()=",SuperType());

SuperType.prototype.getSuperValue = function(){
    return this.property;
}

console.log("SuperType.prototype()=",SuperType.prototype());

function SubType(){
    this.subproperty = false;
}

console.log("SubType()=",SubType());

//继承了SuperType
SubType.prototype = new SuperType();

console.log("SubType.prototype()=",SubType.prototype());

SubType.prototype.getSubValue = function(){
    return this.subproperty;
}

console.log("SubType.prototype()=",SubType.prototype());

var instance = new SubType();
alert(instance.getSuperValue());

//call继承
function A(){
    this.x = 100;
    console.log("A--->this=",this);
}

A.prototype.getX = function(){
    console.log("A.prototype.getX--->this.x=",this.x);
}

function B(){
    console.log("B--->this=",this);
    A.call(this);
}

console.log("B.prototype=",B.prototype);

var n = new B;
console.log(n.x);

//冒充对象继承
/**
 * 冒充对象继承会把父类 私有的+公有的 都克隆一份一模一样的给子类私有的
 */
function A(){
    this.x = 100;
}

A.prototype.getX = function(){
    console.log(this.x);
}

function B() {
    var temp = new A;
    for(var key in temp){
        this[key] = temp[key];
    }
    temp = null;
}

console.log("B=",B);
console.log("B.prototype=",B.prototype);

var n = new B;
console.log("n._proto_=",n._proto_);
console.log(n.x);

//混合式继承
/**
 * 混合式继承就是原型继承+call继承
 * @constructor
 */
function A(){
    this.x = 100;
}

A.prototype.getX = function(){
    console.log(this.x);
}

function B(){
    A.call(this);
}

B.prototype = new A;
console.log("B.prototype=",B.prototype);
// B.prototype.constructor = B;
console.log("B.prototype=",B.prototype);

var n = new B;
n.getX();

//寄生组合式继承
/**
 *
 */

function A(){
    this.x = 100;
}

A.prototype.getX = function(){
    console.log(this.x);
}

function B(){
    A.call(this);
}

B.prototype = Object.create(A.prototype);       //IE6,7,8不兼容
B.prototype = objectCreate(A.prototype);

B.prototype.constructor = B;

console.log("B.prototype=",B.prototype);

var n = new B;
console.dir(n);

function objectCreate(o){
    function fn(){}
    fn.prototype = o;
    return new fn;
}

/**
 * gao 3
 */

function SuperType(name) {
    this.name = name;
    this.colors = ["red","blue","green"];
}

SuperType.prototype.sayName = function(){
    alert(this.name);
}

function SubType(name,age){
    SuperType.call(this,name);
    this.age = age;
}

inheritPrototype(SubType,SuperType);

SubType.prototype.sayAge = function(){
    alert(this.age);
}

function inheritPrototype(subType,superType){
    var prototype = Object(superType.prototype);
    prototype.constructor = subType;
    subType.prototype = prototype;
}


I hope my experience of entering the pit is helpful to you, may the Holy Light be with you

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324349821&siteId=291194637