我正在使用John Resig的简单OOP Class
,它适合于使用“严格使用”并取自SO post。
在所有的例子我看到的Class.extend
使用像这样:简单的JavaScript OOP类
var MyObj = Class.extend({
init:function(){},
prop: "Property"
});
但是我发现了一个大缺点,我在这样的方式使用它 - 我不能有“私人”的变量,所以我不能存储参考this
like var $this = this;
。 我发现我的情况的解决方案,现在我在下面的方式使用Class.extend
:
var MyObj = Class.extend(new function(){
var $this = this;
this.init = function(){};
this.prop = "Property";
});
一切都在我的情况下工作,但我想知道是否有一些事情,可能会导致我的问题,从长远来看?
这样做我的应用程序会消耗更多的浏览器内存?
我有什么替代方法来实现我的需求?
注意:我需要存储$这一点,因为我使用大量的事件和回调,所以我想引用“原始” this
易于访问的对象的所有方法和属性。
编辑:按照要求,这是我的代码示例:
(function() {
"use strict";
window.QuickPlay = Class.extend(new function() {
var $this = this;
this.init = function (initData) {
$this.elementsToHide.push(initData.el);
$(function() {
playProcessStart();
Sys.Application.add_load(function() {
$find("ctl00_ContentPlaceHolderMain_ctrlPlayPopup1").add_closed(function() { $this.setElementsVisibility(""); });
});
$this.setElementsVisibility("hidden");
});
};
this.elementsToHide = [];
this.setElementsVisibility = function (visibility) {
$.each($this.elementsToHide, function (i) {
$("#" + this).css("visibility", visibility);
});
};
});
}());
Ouch,no。我几乎不能相信这对你真的很有用。请告诉我们你如何使用这个具有事件和回调的“类”。也许发布你的实际代码(至少涉及'$ this'的方法)。 – Bergi
@Bergi我添加了这个例子 - 这真的很有效,代码已经通过了QA阶段:) –
在任何对象的内部,你都应该能够访问'this'这个reefers到当前对象。 – travis