JavaScript - object "this"
JavaScript - object "this"
我有两个JavaScript对象。
- Obj1 - 静态类
- Obj2 - 实例
在 Obj1 中添加项目并从 Obj2 运行方法isAdded()
后出现问题。
obj1.func
存储一个函数,该函数包含 Obj2 的关键字 this
。如果我打电话Obj1.func([args])
this
现在是 Obj1 而不是 Obj2。
请问有什么答案吗?
var Obj1=function(){};
Obj1.func=null;
Obj1.addItem=function(vstup){
// code for add - AJAX async ....
// after adding
Obj1.func(id, nazev);
};
// ----------------------------
var Obj2=function(){
this.variable=null;
this.promenna2=null;
this.isAdded=function(){
this.variable="added";
alert("ok");
};
};
// ---------------------
// in body
window.onload=function(){
var instanceObj2=new Obj2();
obj1.func=instanceObj2.isAdded();
obj1.addItem("test");
}
你正在做obj1.func = instanceObj2.isAdded()
这意味着:set
obj1.func
to the result of
instanceObj2.isAdded()
,即:obj1.func = undefined
,因为obj2.isAdded()
什么也不返回。
如果你然后执行obj1.isAdded()
,它运行Obj1.func
,你实际上是在执行undefined
作为一个函数。
要修复它:
obj1.func = function() { instanceObj2.isAdded(); };
在另一个上下文中调用某些内容(又名:运行某些内容并设置"this")
要运行具有不同 this 值的内容,请执行以下操作:
若要设置函数的上下文,可以使用 apply 或调用
function add()
{
var result = this;
for(var i = 0, l = arguments.length; i < l; i++)
result += arguments[i];
return result;
}
var value = 2;
newValue = add.apply(value, [3,4,5]); // = 2 + 3 + 4 + 5;
// newValue = 5
newValue = add.call(value, 3, 4, 5) // same as add.apply, except apply takes an array.
创建具有上下文的新函数
在新浏览器(ie9+)中,可以使用Function.prototype.bind创建一个具有设置上下文(this)的回调,并设置其他参数之前的参数。
callback = func.bind(object);
callback = function() { func.apply(object, arguments); }
callback = func.bind(object, 1, 2);
callback = function() { func.apply(object, [1, 2]); };
在javascript中,这是指当前正在使用的元素,所以它的引用不断变化最好的方法是将(this)存储在变量中。并在您想要的地方使用它。
喜欢
var obj1This=this;
var obj2This=this;
然后使用它们
obj2This.isAdded();
相关文章:
- $(this).prop('property') vs. this.property
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 铬:“;未捕获的语法错误:意外的标记:"
- 可以设置“;文件名"发生错误时显示的内联脚本标记的
- JS表单提交"无法使用Chrome数据保护程序加载此页面.尝试重新加载页面.调试信息:POST CISmtuK
- 检测电话窃听,即:<a href="电话:xxx">在UIWebview上
- 重复“;function(){}.调用(this)"在Uglified JS中
- 这条线是什么意思"this.parentNode.firstChild.nodeName”;在jQuery H
- jqueryui:"类型错误:this.menu.element未定义"
- 为什么获胜't This Vuejs“;Hello World"示例在我的电脑上渲染
- "this.collection.each不是函数;.应该'它不是简单地说“;每个”;
- 为什么不't this replace()替换"我的“;
- 我的onsubmit=“;return onNewUserRegistrationCheck(this)"仍然
- <a href="javascript:foo(this)">通过Window,我想要标记
- 主干——哪个“这个”;是“this"
- How do i formulate "if this.children.has.not.class"
- 鼠标事件监听器&“this"
- <textarea onclick=“;this.value;this.select()">?这是什么
- "类型错误:this.options为null"在OpenLayers.Protocol.HTTP中
- 为什么是全球性的"this.function";如果没有";这个"