js継承を実現する7つの方法
20494 ワード
//1. ( call this )-----------
function Parent1() {
this.name = ' '
}
function Son1() {
Parent1.call(this); // this
}
var s1 = new Son1();
console.log(s1 instanceof Parent1); // false
console.log(s1 instanceof Son1); //true
// : (call); ; ( )
// :Person1
//2. ( )-----------
function Parent2() {
this.name = ' ';
}
function Son2() {
this.type = 'child';
}
Son2.prototype = new Parent2();
var s2 = new Son2();
console.log(s2 instanceof Parent2); // true
console.log(s2 instanceof Son2); // true //
// : ; / ,
// : ; ; ,
//3. ( , )-----------
function Parent3() {}
function Son3(name) {
var s = new Parent3();
s.name = ' '
return s;
}
var s3 = new Son3();
var s31 = Son3();
console.log(s3 instanceof Parent3); // true
console.log(s3 instanceof Son3); //false
console.log(s31 instanceof Parent3); // true
console.log(s31 instanceof Son3); //false
// : , new () (),
// : ,
//4.
function Parent4() {}
function Son4() {
var p = new Parent4();
for (var k in p) {
Son4.prototype[k] = p[k];
}
}
var s4 = new Son4();
console.log(s4 instanceof Parent4); // false
console.log(s4 instanceof Son4); //true
// :
// : , ( )
//5 ( , , , )
function Parent5(name) {}
function Son5(name) {
Parent5.call(this);
}
Son5.prototype = new Parent5();
var s5 = new Son5();
console.log(s5 instanceof Parent5); // true
console.log(s5 instanceof Son5); //true
// : , ; ;
// : , ,
//6. ()
function Parent6() {}
function Son6() {
Parent6.call(this);
}
Son6.prototype = Object.create(Parent6.prototype);
// new , ( , )
// this
Son6.prototype.constrctor = Son6
var s6 = new Son6();
console.log(s6 instanceof Parent6); // true
console.log(s6 instanceof Son6); //true
//
//7.ES6
class People {
constructor(name) {
this.name = name;
}
eat() {
console.log(`${this.name} eat food`)
}
}
//
class Woman extends People {
constructor(name) {
//
super(name);
}
eat() {
//
super.eat();
}
}
let wonmanObj = new Woman('wang');
wonmanObj.eat();
//es6,class , , prototype, new
オリジナルパッケージで継承
// ( )
function extendsClass(Parent, Son) {
function O() {}
O.prototype = parent.prototype;
Son.prototype = new O();
Son.prototype.constrctor = Son;
return Son;
}