JavaScript OOP错误_this值

时间:2016-11-09 15:26:25

标签: javascript oop this self

我们假设我们有以下代码:

var MyClass = (function(){
    var _this;

    function MyClass(inputVal){
        _this = this;
        this.value = inputVal;
    }

    MyClass.prototype.getValue = function(){
        return this.value;
    }

    MyClass.prototype.getValue2 = function(){
        return _this.value;
    }

    return MyClass;
})();

让我们创建该类的两个实例:

var instance1 = new MyClass(10);
var instance2 = new MyClass(20);

现在,如果我们在console.log()中看到我们看到的值:

instance1.getValue();   // 10
instance1.getValue2();  // 20

var MyClass = (function(){
    var _this;

    function MyClass(inputVal){
        _this = this;
        this.value = inputVal;
    }

    MyClass.prototype.getValue = function(){
        return this.value;
    }

    MyClass.prototype.getValue2 = function(){
        return _this.value;
    }

    return MyClass;
})();


var instance1 = new MyClass(10);
var instance2 = new MyClass(20);


console.log(instance1.getValue());
console.log(instance1.getValue2());

为什么会这样?很明显,_this变量获取最新创建的实例属性。如何解决?我需要保留this的副本。谢谢!

修改

这是真实的情况

var HoverEffects = (function(){
    var _this;

    function HoverEffects($nav){
        _this = this;
        this._$activeNav = $nav.siblings('.active_nav');
        this._$hoverableLis = $nav.find('>li');
        this._$activeLi = $nav.find('>li.active');

        if(!$nav.length || !this._$hoverableLis.length || !this._$activeNav.length || !this._$activeLi.length) return;

        if(this._$activeNav.hasClass('bottom')){
            this._$activeNav.align = 'bottom';
            this._$activeLi.cssDefault = {
                left: this._$activeLi.position().left,
                width: this._$activeLi.width()
            };
        }
        else if(this._$activeNav.hasClass('left')){
            this._$activeNav.align = 'left';
            this._$activeLi.cssDefault = {
                top: this._$activeLi.position().top,
                height: this._$activeLi.height()
            };
        }
        else{
            return;
        }

        this._$hoverableLis.hover(
            function(){

                // How to set the correct this inside this function?
                if(this._$activeNav.align === 'bottom'){
                    this._$activeNav.css({
                        left: $(this).position().left,
                        width: $(this).width()
                    });
                }
                else if(this._$activeNav.align === 'left'){
                    this._$activeNav.css({
                        top: $(this).position().top,
                        height: $(this).height()
                    });
                }

            },

            function(){
                // Same here, wrong this
                this._$activeNav.css(this._$activeLi.cssDefault);
            }
        );
    }

    return HoverEffects;
})();

var sideNavHoverMagic = new HoverEffects($('#side-navigation'));
var primaryNavHoverMagic = new HoverEffects($('#primary-navigation'));

1 个答案:

答案 0 :(得分:5)

  

为什么会这样?

每次拨打new MyClass时,_this = this都会被运行。第二次覆盖第一次。

所以_this引用new MyClass(20),这意味着当您从任何 getValue2实例调用MyClass时,20将返回,因为所有 MyClass个实例都指的是相同的_this值。

基于对该问题的评论:

如果您尝试传递绑定到适当上下文的函数,则有多种方法可以确保this引用正确的对象。在继续之前,请阅读"How does the 'this' keyword work?",因为我没有理由在此重复所有内容。

如果您正在绑定事件回调,例如在构造函数中:

function Example(something) {
    something.addEventListener(..event.., this.callback, false);
}
Example.prototype.callback = function () {
    this.doStuff();
    this.doMoreStuff();
};

回调将具有错误的this值,因为它不会被称为this.callback,它只是被称为:

fn = this.callback;
fn(); //no reference to this

你可以通过多种方式解决这个问题。

Function.prototype.bind

您可以为各自实例上的每个实例绑定callback。这非常简洁:

function Example(something) {
    //generate a new callback function for each instance that will
    //always use its respective instance
    this.callback = this.callback.bind(this);
    something.addEventListener(..event.., this.callback, false);
}
Example.prototype.callback = function () {
    this.doStuff();
    this.doMoreStuff();
};

that = this

您可以在构造函数中创建回调(闭包),并在构造函数中引用变量。

function Example(something) {
    //every Example object has its own internal "that" object
    var that = this;
    this.callback = function () {
        //this function closes over "that"
        //every instance will have its own function rather than
        //a shared prototype function.
        that.doStuff();
        that.doMoreStuff();
    }

    something.addEventListener(..event.., this.callback, false);
}

() => {}Fat Arrow Syntax

如果您使用的是ES2015,则可以使用“胖箭头”语法创建不创建新上下文的lambda:

function Example(something) {
    this.callback = () => {
        //the callback function doesn't create a new "this" context
        //so it referes to the "this" value from "Example"
        //every instance will have its own function rather than
        //a shared prototype function.
        that.doStuff();
        that.doMoreStuff();
    }

    something.addEventListener(..event.., this.callback, false);
}