JavaScript - object "this"

JavaScript - object "this"

本文关键字:quot this object JavaScript      更新时间:2023-09-26

我有两个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();