我有以下代码
$(document).ready(function($) {
"use strict";
generalClass = function() {
this.ip = false; // page page
this.ie = false; // IE
this.pp = false; // portfolio page
this.om = false; // organize menu
this.wc = false; // shop
this.sh = false; // side header
// So we can get the correct $this if needed
$this = this;
this.__init();
}
generalClass.prototype = {
__init: function( $check ) {
// Run functions
$this.__format();
$this.__resize();
}
}
});
但我得到$this
未定义。我曾尝试将其写为var $ this但仍然未定义$this.__format();
。我意识到我可以使用它而不是$this
,但在代码中稍后会出现我无法实现的情况。如何设置$this
函数中定义__init()
?所以它引用了generalClass。
谢谢!
答案 0 :(得分:3)
首先,如果您想使用严格模式,则必须将var
(或let
或const
)放在generalClass
和{$this
之前{1}}。
就像那样:
(function () {
"use strict";
var generalClass = function() {
this.ip = false; // page page
this.ie = false; // IE
this.pp = false; // portfolio page
this.om = false; // organize menu
this.wc = false; // shop
this.sh = false; // side header
// So we can get the correct $this if needed
var $this = this;
this.__init();
};
generalClass.prototype = {
__init: function( $check ) {
console.log('$this', $this);
// Run functions
$this.__format();
$this.__resize();
}
}
var instance = new generalClass();
}());
(我将$(document).ready()
更改为IIFE,因此我可以在控制台中运行它。另外,我创建了您的类的实例。)
现在发生了什么? $this
内的__init()
未定义。您必须在$this
内定义__init()
,但问题是:应该分配给它的是什么?
在__init()
的示例中,您实际上可以拨打this
而不是$this
,但正如您已经指出的那样,并非总是可行。
但是让我用更抽象的例子说明它:
(function () {
var GeneralClass = function () {
this.foo = [1, 2, 3];
this.bar = 4;
this.baz = [5];
};
GeneralClass.prototype.someFunction = function () {
console.log('foo', this.foo); // [1, 2, 3]
console.log('bar', this.bar);
var self = this; // storing reference to *this* (oobject for later)
this.baz.forEach(function (item) {
console.log('baz?', this.baz); // undefined, because *this* means here this.baz, and there is no this.baz.baz
console.log('baz!', self.baz); // [5]
});
console.log('foo * bar');
this.foo.forEach(function (item, index) {
console.log('item', index, 'value', item * self.bar);
});
console.log('Both accesible here', this.bar, self.bar);
};
var generalClassInstance = new GeneralClass();
generalClassInstance.someFunction();
}());
在此我将this
分配给self
(就个人而言,我会$this
使用$(this)
,但这只是一个惯例,所以只要你愿意,只要你是一致的)。现在在我的函数内部调用的函数可以使用self
作为外部this
的引用。如果我在子函数中调用了另一个函数,它仍然会指向GeneralClass
的{{1}}。
我希望这是你最感兴趣的。