最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - If a prototype is changed, will this affect current instances? - Stack Overflow

programmeradmin2浏览0评论

Say I have this:

var _JS = function() {
  this.Constants = {
    True: 1,
    False: 0,
    Nil: null,
    Unknown: void(0),
  };
};

var JS = new _JS();

If I change it afterwards (add methods, using _JS.prototype.etc), can I call those methods on JS?

Say I have this:

var _JS = function() {
  this.Constants = {
    True: 1,
    False: 0,
    Nil: null,
    Unknown: void(0),
  };
};

var JS = new _JS();

If I change it afterwards (add methods, using _JS.prototype.etc), can I call those methods on JS?

Share Improve this question edited Dec 28, 2011 at 22:06 Tom van der Woerdt 30k7 gold badges74 silver badges105 bronze badges asked Jun 23, 2011 at 16:54 user142019user142019 3
  • You aren't using a prototype. – SLaks Commented Jun 23, 2011 at 16:56
  • No, I am changing the prototype of a function. :) This is not about the library indeed. – user142019 Commented Jun 23, 2011 at 16:56
  • 1 Um, couldn't you have figure it out yourself testing it? :) – epascarello Commented Jun 23, 2011 at 17:11
Add a ment  | 

4 Answers 4

Reset to default 5

Yes, a prototype change affects all instances of the item whose prototype you modified.

See example of a simple prototype modification: http://jsfiddle/JAAulde/56Wdw/1/

Yes. Modifying a prototype modifies all instances.

A simple test:

var f = function(){}
var g = new f()
f.prototype.trace = function(){alert(1)}
g.trace(); // alerts 1

If a prototype is changed, will this affect current instances?

Yes. If you change the prototype that existing object instances share, it will change for all of them.

The following code would print something:

var ajs = new _JS();
_JS.prototype.do = function () {console.log('something');}
ajs.do();
发布评论

评论列表(0)

  1. 暂无评论