Prototype chain mode (extension)

Prototype chain mode (extension)

this and prototype

In the prototype mode, this is commonly used in two cases:
in the class this.xxx=xxx;this>>the instance of the current class

This>> in a method depends on who is in front of "." when it is executed, and who is this.
1) You need to determine the point of this first (who is this)
2) Replace this with the corresponding

案例五
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

Extend methods on prototypes of built-in classes

案例六
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();

chain:

After executing a method of the array, the next method can be executed immediately

Principle:
Why can ary use the sort method?

Because sort is a public method on Array.prototype, and the array ary is an instance of the Array class, ary can use the sort method.
Arrays can use the properties and methods defined on the Array prototype.
The return value after the execution of sort is completed is a sorted The "array" of the "array" can continue to be executed
. The return value of the reverse execution is an array, and
the return value of the pop execution can continue to be executed. The returned value is the element that was deleted, not an array, so execute push again to report an error

链式:
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);

Guess you like

Origin blog.csdn.net/yilingpupu/article/details/105486689