Created
May 25, 2015 14:59
-
-
Save karenpeng/5b71b54723abd49b9360 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// class A | |
function ParentA(a) { | |
this.a = a; | |
}; | |
ParentA.prototype.displayA = function () { | |
console.log('a: %s', this.a); | |
} | |
// class B | |
function ParentB(b) { | |
this.b = b; | |
}; | |
ParentB.prototype.displayB = function () { | |
console.log('b: %s', this.b); | |
} | |
// Child 继承于 ParentA 和 ParentB | |
function Child(a, b) { | |
// inherits from A and B | |
// ParentA.apply(this, [a]) | |
// ParentB.apply(this, [b]) | |
ParentA.call(this, a) | |
ParentB.call(this, b) | |
}; | |
Child.prototype = Object.create(ParentA.prototype) | |
//Child.prototype = Object.create(ParentB.prototype) | |
// 把 ParentB.prototype 上的东西 copy 过来 | |
//手动吗 | |
//en | |
for(var method in ParentB.prototype){ | |
Child.prototype[method] = ParentB.prototype[method] | |
} | |
Child.prototype.displayAB = function(){ | |
console.log('a: %s', this.a); | |
console.log('b: %s', this.b); | |
} | |
Child.prototype.constructor = Child | |
var child = new Child('a', 'b'); | |
console.log(child) | |
console.log(child.__proto__) | |
console.log(child.a); // a | |
console.log(child.b); // b | |
console.log(child.__proto__.constructor === Child) // true | |
child.displayA(); // a: a | |
child.displayB();// b: b | |
child.displayAB();// a: a, b: b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment