不能在对象字面量内访问另一个函数中的变量

can't access variable in another function inside object literal

本文关键字:函数 另一个 变量 访问 对象 不能      更新时间:2023-09-26

我有以下javascript的代码

var Obj = {
    init: function () {
        this.over = $('<div />').addClass('over');
        $('body').append(this.over);
        $('.click').on('click', this.show);
    },
    show: function () {
        console.log(this.over);
    }
}
Obj.init();

当用户单击.click链接时,它会触发show函数并注销在init函数中创建的dom元素。但问题是它退出未定义。为什么?如何解决?

try this:

var Obj = {
init: function () {
    this.over = $('<div />').addClass('over');
    $('body').append(this.over);
    $('.click').on('click', this.show);
},
show: function () {
    // here the 'this' is the button , not the obj object ..
    console.log($('.over'));
}
}
Obj.init();

另一个选项:

var Obj = {
init: function () {
    this.over = $('<div />').addClass('over');
    $('body').append(this.over);
    var that = this;
    $('.click').on('click', function(e){
       that.show.call(that, e); // calling the show function with call, causing 'this' to be obj
    });
},
 // 'this' is the obj
show: function (e) {
    console.log(this.over);
}
}
Obj.init();

这里的问题是this (Obj)的范围。

使用下面的代码来解决你的问题。

var Obj = {
init: function () {
    this.over = $('<div />').addClass('over');
    $('body').append(this.over);
    $('.click').on('click', $.proxy(this.show, this));
},
show: function () {
    console.log(this.over);
}
};
Obj.init();

了解更多jQuery.proxy

因为jQuery将被点击的DOM元素注入到'this'对象中,而不是'Obj'对象。一个解决方案是闭包:

var Obj = {
  init: function () {
    this.over = $('<div />').addClass('over');
    $('body').append(this.over);
    $('.click').on('click', this.show());
  },
  show: function () {
    var self = this;
    return function () {
        console.log("over:", self.over);
    }
  }
}
Obj.init();

存储在this.show中的函数传递给on。当它被调用时,它不是在Obj的上下文中被调用的,所以this不是Obj

你需要创建一个不依赖于在Obj上下文中被调用的新函数。

最简单的方法是使用bind:

$('.click').on('click', this.show.bind(this));

但是浏览器支持有限。

也可以使用闭包:

var myObj = this;
var show = function () {
    myObj.show()
}
$('.click').on('click', show);

当使用jquery将一个函数绑定到一个事件时,调用该函数的上下文是被点击的dom对象。

var Obj = {
init: function () {
    this.over = $('<div />').addClass('over');
    $('body').append(this.over);
    var that = this;
    $('.click').on('click', function(){ 
        // console.log( this ) will log the dom object
        that.show.call( that ) 
     } );
},
show: function () {
    console.log(this.over);
}
}
Obj.init();