gpt4 book ai didi

javascript - 在原型(prototype)中初始化实例变量如何提高性能

转载 作者:行者123 更新时间:2023-12-01 03:18:14 26 4
gpt4 key购买 nike

Here它说:

Place instance variable declaration/initialization on the prototype for instance variables with value type (rather than reference type) initialization values (i.e. values of type number, Boolean, null, undefined, or string). This avoids unnecessarily running the initialization code each time the constructor is called. (This can't be done for instance variables whose initial value is dependent on arguments to the constructor, or some other state at time of construction.)

它给出了以下示例,而不是:

foo.Bar = function() {
this.prop1_ = 4;
this.prop2_ = true;
this.prop3_ = [];
this.prop4_ = 'blah';
};

用途:

foo.Bar = function() {
this.prop3_ = [];
};

foo.Bar.prototype.prop1_ = 4;
foo.Bar.prototype.prop2_ = true;
foo.Bar.prototype.prop4_ = 'blah';

现在,我创建了 foo.Bar 的两个实例。第二种情况:

foo = {}
f1 = new foo.Bar()
f2 = new foo.Bar()

然后测试:

f1.prop1_ // gives 4
f1.prop1_ = 5 // changed it
f2.prop1_ // still gives 4
Object.getPrototypeOf(f1) === Object.getPrototypeOf(f2) // true

现在我的问题是:虽然 f1f2 共享相同的原型(prototype),但每个原型(prototype)似乎都有不同的范围(封装?),因此,它们有自己的副本prop1_ 的;这意味着发生单独的内存分配。为什么这是性能提升?

最佳答案

它更高效,因为您没有在构造函数中运行一堆赋值代码,这一点应该是显而易见的。它在原型(prototype)上共享相同的值,就像原型(prototype)上共享任何内容一样。

问题是,当您读取f1.prop1_时,它会从原型(prototype)链中查找该值,因为f1本身并不查找没有属性 prop1_但是,当您使用 f1.prop1_ = 5 分配给属性时,它会直接分配给 上的属性f1 对象。 换句话说,赋值会在对象本身上创建属性。原型(prototype)值从此被实例属性遮蔽。这就是为什么实例将具有单独的值。

这对于不可变值来说很好;对于像数组这样的可变值来说这是一个坏主意,因为 f1.arr_.push(foo) 会改变原型(prototype)上的对象,而不是在单个实例上创建属性。

关于javascript - 在原型(prototype)中初始化实例变量如何提高性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45392787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com