【问题标题】:JS cannot access object value from different functionJS 无法从不同的函数访问对象值
【发布时间】:2013-09-08 19:52:15
【问题描述】:

谁能解释为什么第一件事有效而第二件事无效?

function MyObj(val) {
    this.value = val;

    this.myFunc = function(selector) {
        $(selector).html("test: " + this.value);
    }
}

foo = new MyObj("tester");
foo.myFunc("#one"); //This works

func = foo.myFunc;
func("#two"); //This doesnt

怎么样?我怎样才能让它工作?

JSFIDDLE

【问题讨论】:

    标签: javascript jquery function object


    【解决方案1】:

    JavaScript 中函数的this 不是固定的;当你打电话时

    something.somefunc()
    // or something['somefunc']()
    

    this 绑定到 something。当您调用没有对象的函数时,this 会绑定到 undefined(在严格模式下)或全局对象。

    你可以通过保持一个变量来保持正确的this来绕过它:

    function MyObj(val) {
        var obj = this;
    
        this.value = val;
    
        this.myFunc = function(selector) {
            $(selector).html("test: " + obj.value);
        };
    }
    

    ECMAScript 5 在Function.prototype 上提供了一个专门处理这个问题的方法(您通常也应该将myFunc 放在MyObj.prototype 上):

    var func = foo.myFunc.bind(foo);
    func("#two"); // Works now
    

    【讨论】:

    • LOL JavaScript 永远不会停止拖钓我,但是谢谢 :)
    • 通过 foo 时使用 apply() or call() 也应该有效:func.call(foo,'#two');
    • 一个小细节,在严格模式下this 将是undefined。不是null
    • @jaywalking101:哎呀,最近的回答也是如此!谢谢。
    【解决方案2】:

    使用bind()this 的值分配给函数:

    function MyObj(val) {
        this.value = val;
    
        this.myFunc = function(selector) {
            console.log(this); // <--- look your console output
            $(selector).html("test: "+this.value);
        }
    }
    
    foo = new MyObj("tester");
    foo.myFunc("#one");
    
    func = foo.myFunc;
    func.bind(foo)("#two"); //  <---- here
    

    或:

    func = foo.myFunc.bind(foo);
    func("#two");
    

    演示:http://jsfiddle.net/M8Qym/1/

    【讨论】:

    • 虽然字面意思是func.bind(foo)("#two") 应该只是func.call(foo, "#two")
    • 不同之处在于bind创建了一个新的函数,所以他可以使用:func = foo.myFunc.bind(foo);然后func("#two");
    • 这就是我说“字面意思”的原因:)
    猜你喜欢
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多