關於js原型繼承的理解

//原型繼承
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;
}


希望我的入坑經驗對你有所幫助,願聖光與你同在

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章