Javascript:修改原型不会影响现有实例 [英] Javascript : Modifying Prototype doesn't affect existing Instances

查看:44
本文介绍了Javascript:修改原型不会影响现有实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个原型的2个实例,更改了原型中的功能,这两个实例中都反映了更改(很好).但是,当我通过删除功能修改原型时,该功能对于现有实例仍然存在.

 函数A(){this.name =酷";}A.prototype = {howCool:function(){返回this.name +"er";}};var a1 = new A(),a2 =新的A();a1.name =热";//第1行console.log(a1.howCool());//第2行console.log(a2.howCool());A.prototype = {};//第3行console.log(a1.howCool());//第4行var a3 = new A();console.log(a3.howCool());  

第1行和第2行按预期方式工作,将原型设置回空后,第4行显示未定义状态.但是,第3行仍显示函数定义.

解决方案

基本上,您正在重新分配功能 A prototype 属性以指向新对象.这不会影响旧对象,因此也不会影响以前的实例.

这是正在发生的事的例证.

执行此代码后:

 函数A(){this.name =酷";}A.prototype = {howCool:function(){返回this.name +"er";}};var a1 = new A(),a2 =新的A(); 

情况如下:

然后在执行此代码之后:

  A.prototype = {};var a3 = new A(); 

A.prototype 指向一个新对象,但

如果要实际删除该方法,则必须编辑原始对象,而不是指向新对象.

要从原型中实际删除 howCool()方法,可以使用以下方法:

 删除A.prototype.howCool 

哪个会给:

现在,将来的任何实例,例如 a3 和先前的实例,都仍将指向同一对象,但是该对象将没有 howCool()方法.

I created 2 instances of a prototype, changed a function in prototype, changes reflected in both the instances (Great). However, when I modified the prototype by removing the function, the function still existed for the existing instances.

function A() {
  this.name = "cool";
}

A.prototype = {
  howCool: function() {
    return this.name + "er";
  }
};

var a1 = new A(),
  a2 = new A();

a1.name = "hot";
//line1
console.log(a1.howCool());
//line2
console.log(a2.howCool());

A.prototype = {};

//line3
console.log(a1.howCool());

//line4
var a3 = new A();
console.log(a3.howCool());

Line 1 and 2 are working as expected and after setting the protoype back to empty, line 4 is showing undefined which is expected. line 3 however is still showing the function definition.

解决方案

Essentially you're reassigning the prototype property for the function A to point to a new object. This does not affect the old object and thus doesn't affect prior instances.

Here's an illustration of what is happening.

After this code executes:

function A() {
  this.name = "cool";
}

A.prototype = {
  howCool: function() {
    return this.name + "er";
  }
};

var a1 = new A(),
  a2 = new A();

the situation is the following:

Then after this code executes:

A.prototype = {};

var a3 = new A();

The A.prototype points to a new object but the [[Prototype]] property for old instances still points to the old object.

If you want to actually remove the method, you must edit the original object, not point to a new one.

To actually remove howCool() method from the prototype, something like this would work:

delete A.prototype.howCool

Which would give:

Now any future instances, such as a3, and the prior ones, would all still point to the same object but that object won't have the howCool() method.

这篇关于Javascript:修改原型不会影响现有实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆