对象原型不会“实时更新" [英] Object prototype does not "live update"

查看:32
本文介绍了对象原型不会“实时更新"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下一段代码:

var Test = function () {
};
Test.prototype.doSomething = function() {
  return "done";
};

现在,我创建了一个 Test 对象

Now, I create an object of Test

var t = new Test();
alert(t.doSomething());    // Correct alerts "done"

现在我在原型中添加另一个方法:

Now I add another method to the prototype:

Test.prototype.fly = function() { return "fly"; };
alert(t.fly());       // Correctly alerts "fly" (existing objects get "live udpated")

现在,我让原型指向一个空白对象:

Now, I make the prototype point to a blank object:

Test.prototype = {};
alert(t.doSomething());    // Continues to alert "done", but why?
alert(t.fly());            // Continues to alert "fly", but why?

var t2 = new Test();
alert(t.doSomething());    // As expected, this does not work

  1. 当我向原型添加方法时,它会正确反映所有新对象和现有对象

  1. When I add a method to prototype, it reflects correctly on all new and existing objects

当我通过执行 .prototype = {}; 来消隐"原型时,它只会消隐"新实例,而不是现有实例.为什么?

When I "blank" out the prototype by doing <name>.prototype = {};, it only "blanks" out new instances, but not existing ones. Why?

推荐答案

打个比方:

var a = {foo : 'bar'};
var b = a; //the same object as a
var c = a;
var d = a;

a.apple = 'orange';

a = 1;  //a === 1. b, c and d stay the same, pointing to the object with apple

我在这里所做的是替换 a 指向的内容,而不是对象本身.

What I did here is replace what a was pointing, but not the object itself.

当您添加 fly 时,您正在修改所有实例共享的单个原型对象,即 Test.prototype 当前指向的对象.

When you added fly, you are modifying that single prototype object which all instances share, the object that Test.prototype is currently pointing to.

但是当您将一个空白对象分配给 Test.prototype 时,您修改了 Test.prototype 所指向的内容.它不会修改现有实例所指向的内容.但是从现在开始,任何新实例现在都将使用 Test.prototype 上的新对象作为它们的原型对象.

But when you assigned a blank object to Test.prototype, you modified what Test.prototype was pointing to. It does not modify what the existing instances are pointing to. But from this point on, any new instances will now use the new object on Test.prototype as their prototype object.

如果您熟悉 C,我宁愿将 JS 变量视为指针而不是引用.

If you are familiar with C, I'd rather think of JS variables as pointers rather than references.

这篇关于对象原型不会“实时更新"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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