要約すると、特定の概念は私が引用したブログ投稿で見ることができます。
引用:RuanYifengのブログ
継承の種類が1つしかない、それがプロトタイプチェーン継承であると言うのはなぜですか。実装方法はたくさんありますが、本質的にはこれだけです。
結論は5番目の要約セクションにあります。
1.空のオブジェクトの中間継承(関数タイプ+プロトタイプチェーンメソッド)
利点:
- 空のオブジェクトはメモリを占有しません
- 子オブジェクトのコンストラクターを変更しても、親オブジェクトのコンストラクターは変更されません
- es6でのextendの実装だと思います
成し遂げる:
function extend(child,parent){
// parent.apply(child); 不能在这里加,不然this.type就是child的静态方法了
var f = function(){
}
f.prototype = parent.prototype;
child.prototype = new f();
child.prototype.constructor = child; // 注意:默认指向parent,这里改成自己
child.uber = parent.prototype; // 备用属性
}
リトルチェスナットワン:
var cat = function(name){
this.name = name;
this.type = 'dongwu'
}
cat.prototype.getName = function(){
console.log(`this name is: ${this.name}`)
}
cat.prototype.getType = function(){
console.log(`this type is: ${this.type}`)
}
var catFood = function(user, name){
cat.apply(this)
this.user = user;
this.name = name;
}
extend(catFood, cat);
catFood.prototype.getUser = function(){
console.log(`this user is: ${this.user}`)
}
console.log(catFood instanceof cat) //false
console.log(catFood.uber === cat.prototype) //uber属性的使用。
var foot = new catFood('maoliang', 'maomi')
foot.getName();
foot.getUser();
foot.getType();
console.log(foot instanceof catFood) //true
console.log(foot instanceof cat) //true
2.コピー継承(関数型+プロトタイプチェーンコピー方法)
長所と短所:
プロトタイプのチェーン継承を破壊する最初のnull値継承メソッドほど良くはないと思います。
実装は次のとおりです。
function extend(child,parent){
var c = child.prototype;
var p = parent.prototype;
for(var i in p){ // 使用for in来枚举所有属性(可枚举和不可枚举)
c[i] = p[i]
}
child.uber = parent.prototype;
}
3.非コンストラクター継承(オブジェクトタイプ+プロトタイプチェーンメソッド)
長所と短所:
主にオブジェクトタイプ用であり、オブジェクトなどの複雑なタイプはサポートしていません。
これは、Object.create()関数の擬似コードでもあります。
リトルチェスナット2号:
var extent = function(parent){
var f = function(){}
f.prototype = parent;
return new f();
}
var father = {
isfather: 'yes'
}
var son = extent(father);
console.log(son.__proto__ === father) // true
son.isSon = 'yes'
console.log(son.isfather) //yes
console.log(son.isSon) //yes
4.プロトタイプチェーンなしのディープコピー継承(オブジェクトタイプ+コピーメソッド)
長所と短所:
jqueryの実装
成し遂げる:
function extendCopy(p, c) {
var c = c || {};
for (var i in p) {
if (typeof p[i] === 'object') {
c[i] = Array.isArray(p[i]) ? [] : {};
extendCopy(p[i], c[i])
} else {
c[i] = p[i];
}
}
return c;
}
リトルチェスナットNo.3:
var Chinese = {
nation: '中国',
birthPlaces: ['北京', '上海', '香港']
};
var Doctor = extendCopy(Chinese);
Doctor.birthPlaces.push('厦门');
console.log(Doctor.nation); // 中国
console.log(Doctor.birthPlaces); //北京, 上海, 香港, 厦门
console.log(Chinese.birthPlaces); //北京, 上海, 香港
5.まとめ(強調)
- 上記の実装方法は4つありますが、継承は関数用だと思います。結局、instanceofの定義によれば、オブジェクトにはプロトタイプがありません。
- したがって、継承の種類は関数のプロトタイプチェーン継承のみです(プロトタイプチェーンコピーメソッドは継承を破棄し、カウントできません)。
- ただし、オブジェクトには、プロトタイプチェーンとコピーの2種類の「継承」があります。プロトタイプチェーンはObject.createの実現であり、コピーはjqueryの実現です。
- jqueryの実装では、関数のコピーはありません。特定のソースコードを参照できます:article
- 私が思うにYUIライブラリの消失がES5およびES6に関連している可能性があり、かつES5およびES6はYUIライブラリからいくつかのコードを借りている場合があります。