【发布时间】:2011-08-12 01:59:59
【问题描述】:
我阅读了很多 JavaScript 代码,看到了很多不同风格的所谓的类。我正在开发一个轻量级 DOMish 类,它包含我的模板脚本的最低限度,在 Node.JS 上运行(它使用 JSON 将 DOMish 实例转换为另一个 DOMish 实例,然后将其序列化为 HTML,缓存原始 DOMish 实例并根据模板请求克隆它)。
以上与我的问题无关。阅读http://www.phpied.com/3-ways-to-define-a-javascript-class/,第 1.2 节后。内部定义的方法
1.1 的一个缺点。就是每次创建新对象时都会重新创建getInfo()方法。
定义类的方式,如第 1.1 节所述,是(稍微修改以反映我自己的情况,使用本地/私有变量):
function Apple (type) {
var that = this;
// local-variable
var color = 'red';
// local-(extern)-function
var infoProvider = function() { // inner-function
// note the danger of this and that!
return that.color + ' ' + that.type + ' ' + this.type;
};
this.__defineGetter__("type", function() { return type; });
this.getInfo = function(otherContext) {
return infoProvider.call(otherContext); // other "this" scope
};
}
var apple = new Apple('iPod');
apple.getInfo({type: 'music player'}); // 'red iPod music player'
我碰巧使用了相同的样式,因为该函数现在可以访问在构造函数中定义的本地/私有变量和函数。但是“每次创建新对象时都会重新创建[函数]”这句话。吓到我了(性能明智)!当我使用使用 V8 的 Node 时,我一直认为函数只创建一次并以某种方式缓存,当在不同的对象上调用时,只使用不同的上下文(thises 和thats) .
我应该害怕“娱乐”吗?与基于原型的函数相比,它有多糟糕?还是这纯粹是审美(人们喜欢将东西放在一起,在构造函数中,VS,人们喜欢原型)?
【问题讨论】:
标签: javascript performance function scope