更改其原型中的当前对象

Change current object in its prototype

本文关键字:对象 原型      更新时间:2023-09-26

如何更改对象本身,指向对象的指针,创建另一个对象。

Array.prototype.change=function(b){
    // this=b; //does not work
}
a=[1,2,3];
b=[3,2,1];
a.change(b);
console.log(a); // Should be [3,2,1]

再比如:

String.prototype.double=function(){
    //this+=this; //like str+=str
}
str="hello";
str.double();
console.log(str); // echo "hellohello"

您可以像这样定义原型:

Array.prototype.change = function (b) {
   this.length = 0;
   this.push.apply(this, b);
}

在内部,它将清除现有数据并从参数中的数组中添加数据。

这不会使数组成为完全相等的数组b(它们仍然是具有不同引用的不同对象,a == b false),但两者中的数据将是相同的。