范围关于"使用严格"和$这个

时间:2016-08-26 17:47:20

标签: javascript jquery

我有以下代码

$(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。

谢谢!

1 个答案:

答案 0 :(得分:3)

首先,如果您想使用严格模式,则必须将var(或letconst)放在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}}。

我希望这是你最感兴趣的。