javascript - 如何在其成员函数之一中引用对象?

标签 javascript oop this

我有以下内容:

var o = {f: function(fn) {
    fn.call(o);
}};
var ob = {f: function() {
    o.f(function() {
        this.x = 2; //HERE: how can this reference ob?
        //ob.x = 2;
    });
}};
ob.f();
ob.x; // undefined

o.f(fn)电话 fn其中 this绑定(bind)到 o。

在 HERE,我想使用 this访问ob。 然而,当ob.f被称为,this绑定(bind)到 o . 我认为 JQuery 是这样工作的。 例如:

$(...).blah(function() {
    this // this is bound to $(...) jquery object.
    ...
};

我现在做的是:

var Ob = function() {
    var self = this;
    self.f = function() {
        o.f(function() { self.x = 2; };
    };
};
var ob = new Ob();
ob.f();
ob.x; // 2

但出于风格原因我不喜欢上面的内容:

  1. 使用new运算符听起来太经典了 OOP。
  2. 定义 <strong>class</strong> Ob使用 function不直观(至少在开始时)。

这就是我尝试定义 ob 的原因带有对象字面量。 但是我找不到引用对象的方法 ob在一个函数中 使用设置 this 的方法调用除ob 以外的其他对象.

我可以做类似下面的事情:

var ob = {f: function() {
    o.f(function() {
        self.x = 2;
    });
}};
var self = ob;
ob.f();
ob.x;

但我不知道如何考虑以上因素。 我试过:

function obj(o) {
    return function() {
        var self = o;
        return o;
    }();
}
var ob = obj({f: function() {
    o.f(function() {
        self.x = 2;
    });
}});
ob.f();
ob.x;// ReferenceError: self is not defined

那么,有没有办法在对象内部的函数中引用对象 可靠地(this 可以根据上下文绑定(bind)到任何东西)?

最佳答案

在 JavaScript 中,函数是对象,有两种调用函数的方法:

call(scope, arg1, arg2, ...);
apply(scope, args);  // args is an array of arguments to call the function with

第一个参数“scope”是函数内绑定(bind)到“this”的对象。所以,下面的例子是等价的:

obj.method(1, 2, 3);
obj.method.call(obj, 1, 2, 3);
obj.method.apply(obj, [1, 2, 3]);

在您的第一个示例中,您使用“o”作为范围调用传递给 o.f() 的函数:

var o = {f: function(fn) {
    fn.call(o);
}};

因此你传入的函数 'ob' 引用 'o' 是这样的:

var ob = {f: function() {
    o.f(function() {
        this.x = 2; //HERE: how can this reference ob?
        //ob.x = 2;
    });
}};

在“HERE”这一行中,“this”实际上是“o”。

您可以尝试以下方法:

var ob = {f: function() {
    var self = this;
    o.f(function() {
        self.x = 2; // self is ob now
    });
}};

或者您可以修改函数“o.f”以获取范围参数:

var o = {f: function(fn, scope) {
    fn.call(scope || this); // Uses the given scope or this (= 'o') if no scope is provided
}};

然后你可以在'ob'中传递'this':

var ob = {f: function() {
    o.f(function() {
        this.x = 2; // 'this' will be the 'outer' this
    }, this); // Here: this as scope
}};

关于javascript - 如何在其成员函数之一中引用对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/569654/

相关文章:

javascript - AWS S3 Javascript SDK 重新发送请求失败

language-agnostic - DoSomethingToThing(Thing n) vs Thing.DoSomething()

javascript - 无法弄清楚如何在 jQuery 中正确使用 $(this) 来获取悬停元素

javascript - Jquery - 使用 "this"获取属性

javascript - JS This 和模板字面量实践

javascript - 如何在java中的JAX-WS服务器端添加CORS支持

javascript - iPhone 上的 Knockout.js 问题 - 下拉列表问题

javascript - MVC4 Devexpress 排序、分组和过滤不起作用

java - 如何避免为未实现公共(public)接口(interface)的相同库方法编写许多包装器?

javascript - 格式化来自 firestore 的 JSON 数据