Prototype chain pattern (in depth)

Bulk setting public properties and methods on prototypes

案例一
普通:
function Fn(){
    
    
this.x = 100;
}
Fn.prototype.getX = function(){
    
    
console.log(this.x);
};
Fn.prototype.getY = function(){
    
    
console.log(this.x);
};
Fn.prototype.getZ = function(){
    
    
console.log(this.x);
};
var f1 = new Fn;

1. Make an alias

Assign the address pointed to by the original prototype to our pro, now they operate on the same memory space

案例一拓展
function Fn(){
    
    
this.x = 100;
}
var pro = Fn.prototype;
pro.getX = function(){
    
    
console.log(this.x);
};
pro.getY = function(){
    
    
console.log(this.x);
};
pro.getZ = function(){
    
    
console.log(this.x);
};
var f1 = new Fn;

2. Refactoring the prototype object method

Open up a heap memory by yourself, store our public properties and methods, and replace the one originally developed by the browser for Fn.prototype

案例一拓展:
function Fn(){
    
    
this.x = 100;
}
constructor:Fn,
Fn.prototype = {
    
    
a:function(){
    
    
},
b:function(){
    
    
}
};
var f= new Fn;
f.a();>>可以执行
console.log(f.constructor);
>>object

Knowledge point

1. There is only a constructor in the heap memory created by the browser for Fn.prototype, but there is no such property in our own development, so the constructor points to the object instead of Fn.
In order to be consistent with the original, we need to manually Add constructor pointing

2. Add public properties
to built-in classes in this way Add array deduplication methods to built-in classes Array

案例二
普通
Array.prototype.unique = function(){
    
    
};
或者
Array.prototype = {
    
    
constructor:Array,
unique:function(){
    
    
}
};
console.dir(Array.prototype);

Our method will replace the properties and methods that have existed on the prototype before, so if we modify the built-in class in this way, the browser will block it.

But we can modify the built-in methods one by one. When we add methods to the prototype of the array in the following way, if the method name is duplicated with the original built-in method, the built-in method will be modified and
we will add it to the prototype of the built-in class later. To add methods, you need to add a special prefix to the name

案例二拓展
Array.prototype.sort=function(){
    
    
console.log(this);
>>this是ary当前操作的这个数组
}
var ary = [1,2,2,3,2,1,3,4,1,2];
ary.sort();
console.log(ary);

Guess you like

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