简体   繁体   English

在构造函数中创建JavaScript原型

[英]JavaScript prototype creation in constructor

What happens in memory when you add to an object's prototype in the constructor? 当您在构造函数中添加到对象的原型时,内存中会发生什么? Does it get it recreated every time you make a new object? 每次创建新对象时都会重新创建它吗?

For example: 例如:

function Foo(){
  Foo.prototype.bar = function() {
    console.log("bar func called");
  }
}    
var x = new Foo();
x.bar();
var y = new Foo();
y.bar();

The "nature" of the code doesn't matter, it's executed every time you call it. 代码的“性质”无关紧要,每次调用时都会执行。 This means that yes, every time you call new Foo() the function bar of the prototype is reassigned. 这意味着,是的,每次调用new Foo() ,都会重新分配原型的功能bar

This also means that every Foo object out there get a new bar method, even those that already existed. 这也意味着每个Foo对象都会获得一个新的bar方法,即使那些已经存在的对象也是如此。

每次调用该函数时,放入该函数中的所有代码都会运行,即使该代码分配了原型的属性也是如此。

Yes it does. 是的,它确实。 The creation code will be executed each time you instantiate Foo. 每次实例化Foo时都会执行创建代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM