- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
var A = function(x){
var that = this;
this.a = x;
}
A.prototype = {
init: function(){
alert(this.a); // as that is not found :s
}
};
var a = new A(1);
var b = new A(2)
a.init.call(b);
// I want to alert number 1, how to do it?
我需要它,因为我使用 jQuery 事件。
我的问题得到了回答,但是这有一些问题,我必须定义一个局部变量并为每个事件创建一个闭包……恶心!
var that = this;
this.view.skinAppliedSignal.add(function(){
that.onSkinApplied();
});
//那么在 onSkinApplied 中这是正确的。有什么办法可以不那么笨拙地完成这项工作吗?
最佳答案
一般情况下,您不能那样做。函数运行时唯一存在的 this
是由调用建立的 this
。
当您建立事件处理程序时,您可以将事物“捕获”在闭包中:
function something() {
$('.whatever').each(function() {
var whatever = $(this);
whatever.find('button').click(function() {
whatever.hide();
});
});
}
在该示例中,“whatever”用于保存来自“each”循环的元素,以便连接到按钮元素的事件处理程序可以访问它。
edit — 根据评论和对问题的更新,很明显可能需要的是类似于“.bind()”函数的东西,它是 ES5 的一部分(由一些库,例如 Prototype、Functional 和 jQuery)。通过使用“绑定(bind)”,您基本上可以将您选择的任何函数包装在另一个 函数中,这样您的函数将始终在 this
设置为某个特定对象的情况下被调用。
关于javascript - 当通过调用 method.call(otherObject) 覆盖 this 时,如何获取对 this 的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4695814/
假设我有这样一个类: class Foo(declarativeBase): bars1 = relationship(Bar.Bar, secondary=foos_to_bars1, c
这个问题在这里已经有了答案: Convert ArrayList to String[] array [duplicate] (6 个答案) 关闭 10 年前。 我有课 public class A
这个问题已经有答案了: Accessing an object property with a dynamically-computed name (19 个回答) 已关闭 3 年前。 我有 2 个对
我有一个对象,该对象具有另一个对象列表的成员。即: public class ObjA { public int Id { get; set; } Other members....
有一个非常相关的问题:Create List from List但是它不处理同时删除重复项。 我有以下类示例: class Widget { public string OwnerName;
var A = function(x){ var that = this; this.a = x; } A.prototype = {
我是一名优秀的程序员,十分优秀!