プロトタイプチェーンモード(拡張)

プロトタイプチェーンモード(拡張)

これとプロトタイプ

プロトタイプモードでは、これは一般的に2つの場合に使用され
ます。クラスではthis.xxx = xxx;this>>現在のクラスのインスタンス

メソッド内のこれ>>は、実行時に「。」の前に誰がいて、誰がこれであるかによって異なります
。1)最初にこれのポイントを決定する必要があります(これは誰ですか)
2)これを対応するものに置き換えます

案例五
function Fn(){
    
    
this.x=100;
this.y=200;
this.getY:function(){
    
    
console.log(this.y);
};
}

Fn.prototype={
    
    
constructor:Fn,
y=300,
getX:function(){
    
    
console.log(this.x);
},
getY:function(){
    
    
console.log(this.y);
}
};
var f=new Fn;
f.getX();
>>100>>console.log(f.x)
f.__proto__.getX();
>>this是__proto__>>console.log(__proto__)>>undefined
f.getY();
>>200
Fn.prototype.getX();
>>undefined
f.__proto__.getY();
>>300
Array.prototype.myUnique=function(){
    
    
>>this
};
var ary[];
ary.myUnique();
 >>this是ary
Array.prototype.myUnique();>>this是Array.prototype

組み込みクラスのプロトタイプのメソッドを拡張する

案例六
Array.prototype.myUnique=function(){
    
    
// >>this>>ary
var obj={
    
    };
for(var i=0;i<this.length;i++){
    
    
var cur=this[i];
if(obj[cur]==cur){
    
    
this[i]=this[this.length-1];
this.length--;
i--;
continue;
}
obj[cur]=cur;
}
obj=null;
};
var ary[10,12,13,11,16,18,31,21,10];
普通:
ary.sort(function(a,b){
    
    
return a-b;
});
ary.reverse();
ary.pop();

鎖:

配列のメソッドを実行した後、次のメソッドをすぐに実行できます

原則:
なぜaryはsortメソッドを使用できるのですか?

sortはArray.prototypeのパブリックメソッドであり、array aryはArrayクラスのインスタンスであるため、aryはsortメソッドを使用
できます。配列はArrayプロトタイプで定義されたプロパティとメソッドを使用できます。
ソートが完了しましたソート済み「配列」の「配列」は実行を継続できます
。逆実行の戻り値は配列であり
、ポップ実行の戻り値は実行を継続できます。戻り値は配列ではなく削除された要素なので、もう一度プッシュを実行してエラーを報告してください

链式:
ary.sort(function(a,b){
    
    
return a-b;
}).reverse().pop();
ary.myUnique();
案例七
Array.prototype.myUnique=function(){
    
    
// >>this>>ary
var obj={
    
    };
for(var i=0;i<this.length;i++){
    
    
var cur=this[i];
if(obj[cur]==cur){
    
    
this[i]=this[this.length-1];
this.length--;
i--;
continue;
}
obj[cur]=cur;
}
obj=null;
return this;>>为了实现链式写法
};
var ary[10,12,13,11,16,18,31,21,10];
ary.myUnique();.sort(function(a,b){
    
    
return a-b;
});
console.log(ary);

おすすめ

転載: blog.csdn.net/yilingpupu/article/details/105486689