我在尝试构建一个简单的 jQuery 插件时遇到了一个问题,我猜这与范围有关。
问题简而言之:类 (A) 创建一个对象 (B),其中属性 (C) 设置为类方法 (D) 之一。如何通过属性(C)访问类A中未包含在对象(B)内的方法?
更长的版本(下面的代码):我在插件内声明一个对象(我们称之为 publicMethods),由一堆方法组成。这些方法应该是一些默认方法(在插件内部声明),或者如果用户在初始化插件时声明了自己的方法,则可以是用户声明的方法。
这个想法是,当用户定义自己的自定义方法时,该函数中应该有一些可供她访问的函数和变量(例如 this.someVar)。
但这会带来一些限制。
我希望默认方法能够访问一些不包含在对象 publicMethods 内的内部函数和变量。但是,当我通过它们所在的对象访问这些方法时,而不是直接调用它们,我无权访问不在该对象内部的其他变量/函数。
我正在尝试找到一种方法让默认方法可以访问它的同级类。我知道我可以在调用该方法之前执行一些条件语句(如果它是用户定义的或不是),甚至声明一个指向“this”的全局变量,但我宁愿保持它干净。
var Plugin = function (opt) {
this.settings = $.extend({
"someVar" : "Value",
"someFunc" : null
});
this.anotherVar = "Hello World";
this.setPublic();
this.run();
}
Plugin.prototype = {
setPublic: function() {
this.publicMethods.someFunc = this.someFunc;
if ($.isFunction(this.settings.someFunc)) {
this.publicMethods.someFunc = this.settings.someFunc;
} else {
this.publicMethods.someFunc = this.someFunc;
}
},
someFunc: function(arg) {
return this.anotherVar; // returns type error the second time
},
run: function () {
this.someFunc();
this.publicMethods.someFunc();
}
}
最佳答案
来自 MDN:Function.prototype.bind()
:
The
bind()
method creates a new function that, when called, has itsthis
keyword set to the provided value, [...].
所以以下应该有效:
setPublic: function() {
this.publicMethods.someFunc = this.someFunc.bind(this);
if ($.isFunction(this.settings.someFunc)) {
this.publicMethods.someFunc = this.settings.someFunc.bind(this);
}
// This is redundant anyway:
/* else {
this.publicMethods.someFunc = this.someFunc.bind(this);
}*/
},
关于javascript - 对象内部的对象内部的范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31640141/