2013-03-21 62 views
3

我具有以下的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功能和注销中创建的DOM元素代码init功能。 但问题是,它然后注销未定义。为什么?如何解决它?

回答

4

试试这个:

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(); 
+0

希望它有帮助,并解决您的问题,如果您需要帮助了解某事,请告诉我。 – IdanHen 2013-03-21 07:31:16

+0

谢谢你的帮助。还有一件事你可以看看这个http://jsfiddle.net/SQGsZ/1/。为什么我没有注销? – 2619 2013-03-21 07:48:01

+1

Obj.me; => Obj.me(); //在第9行! – IdanHen 2013-03-21 07:50:51

2

这里的问题是,thisObj)的范围。

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

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

+0

上下文,而不是范围。 – Quentin 2013-03-21 07:36:48

0

存储在this.showon功能。当它被调用时,它不会在Obj的上下文中调用,所以this不是Obj

您需要创建一个不依赖于在Obj环境中调用的新函数。

要做到这一点,最简单的方法是使用bind

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

但是,这limited browser support

您也可以使用闭包:

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

当一个函数结合使用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(); 
1

因为jQuery注入了与'Obj'对象相对的'this'被点击的DOM元素。一种解决方案是关闭:

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(); 
相关问题