强迫上下文 [英] Forcing the context

查看:101
本文介绍了强迫上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个类,我有一个私有属性和一个公共访问方法:

I have this class where I have a private property and a public method for access:

Person = function () {
    this.Name = "asd";

    var _public = new Object();
    _public.Name = function (value) {
        if (value == undefined) { //Get
            return this.Name
        } else {
            this.Name = value; //Set
        }
    };

    return _public;
};

我想强制 _public.Name 访问 this.Name

我知道关闭的技巧,但我想知道是否我可以强制上下文。

I know the technique of closure, but I want to see if I can force a context.

我找到了一种技术来扩展对象功能:

I found a technique to do it, extend object Function:

Function.prototype.setScope = function (scope) {
    var f = this;

    return function () {
        f().apply(scope);
    }
}

我的班级成为:

Person = function () {
    this.Name = "asd";

    var _public = new Object();
    _public.Name = function (value) {
        if (value == undefined) {
            return this.Name
        } else {
            this.Name = value;
        }
    }.setScope(this);

    return _public;
};

所以我可以正确强制上下文,但我无法传递但不能返回 this.Name

So I can force correctly the context, but I can not pass value and can not, however, return this.Name.

推荐答案

f().apply(scope);

只需

f.apply(scope);

() <$ c后$ c> f 。)你想在函数 f 上使用 apply 函数对象,而不是调用函数 f 并访问对其返回值应用

(No () after f.) You want to use the apply function on the function f object, not call the function f and access apply on its return value.

要传递 setScope 中函数的参数,请添加:

To also pass on the arguments that your function in setScope receives, add this:

f.apply(scope, arguments);

arguments 是所有函数的隐式参数,这是在运行时传递给函数的实际参数的伪数组。 apply 接受任何类似数组的东西作为其第二个参数来指定调用底层函数时使用的参数。

arguments is an implicit argument to all functions, which is a pseudo-array of the actual arguments passed to the function at runtime. apply accepts any array-like thing as its second parameter to specify the arguments to use when calling the underlying function.

我也让它返回返回值:

return f.apply(scope, arguments);

所以 setScope 变为:

Function.prototype.setScope = function (scope) {
    var f = this;

    return function () {
        return f.apply(scope, arguments);
    }
}

实例

请注意此函数的常用名称及其在新函数中的名称 ECMAScript5标准 bind (第15.3.4.5节; ECMAScript5的 bind 也允许你咖喱参数,这不是由此实现完成的)。 setScope 是一个特别不幸的名称,因为它没有设置范围,它设置上下文

Note that the usual name for this function, and the name it has in the new ECMAScript5 standard, is bind (Section 15.3.4.5; ECMAScript5's bind also lets you curry arguments, which isn't done by this implementation). setScope is a particularly unfortunate name, because it doesn't set the scope, it sets the context.

说了这么多,你没有理由在 setScope $ c>构造函数。你可以这样做:

Having said all that, there's no reason you need setScope in your Person constructor. You can just do this:

Person = function () {
    var self = this;

    this.Name = "asd";

    var _public = new Object();
    _public.Name = function (value) {
        if (value == undefined) {
            return self.Name;
        } else {
            self.Name = value;
        }
    };

    return _public;
};

实例

但是使用 bind (又名 setScope )在你不想在你正在进行的上下文中使用新闭包的地方非常有用。

But using bind (aka setScope) can be useful in places where you don't want a new closure over the context in which you're doing it.

偏离主题:您指定的方式会破坏人们可能期望工作的某些事情,例如:

Off-topic: The way you're specifying Person will break certain things people might expect to work, such as:

var p = new Person();
alert(p instanceof Person); // Expect "true", but in your case will be "false"

...因为你'替换为您创建的对象 new ,但是从构造函数中返回一个不同的对象(这会覆盖默认值)。

...because you're replacing the object new created for you, but returning a different object out of your constructor (which overrides the default).

不是创建一个新对象并在构造函数中返回它,而是允许 new 为你构造的对象成为对象(因此维持人关系,但你仍然可以获得真正的私有变量并使用访问者:

Rather than creating a new object and returning that in your constructor, allow the object constructed for you by new to be the object (and thus the Person relationship is maintained), but you can still get truly private variables and use accessors:

function Person() {
    // Private variable
    var name = "asd";

    // Accessor function
    this.Name = function(value) {
        if (typeof value === "undefined") {
            return name;
        }
        name = value;
    };
}

实例

正如您所看到的,这非常简单,它保留了 instanceof 关系。请注意,我们根本没有在名称中对我们对 name 的引用进行限定,因此我们使用的是本地构造函数调用中的变量,其中我们的名称函数已经创建。

As you can see, this is dramatically simpler, and it preserves the instanceof relationship. Note that we're not qualifying our references to name within Name at all, and so we're using the local variable in the constructor call in which our Name function, which closes over it, was created.

我是也可以自由地给构造函数一个 name ,因为我不是匿名函数的粉丝。我应该给访问者一个名字:

I've also taken the liberty there of giving the constructor function a name, because I'm not a fan of anonymous functions. I should have given the accessor a name as well:

function Person() {
    // Private variable
    var name = "asd";

    // Accessor function
    this.Name = Person_Name;
    function Person_Name(value) {
        if (typeof value === "undefined") {
            return name;
        }
        name = value;
    }
}






非主题2 :JavaScript代码中的压倒性惯例是对函数名使用构造函数的初始上限(例如 Person ),而不是其他类型的函数(如 Name )。当然,你可以自由地做任何你喜欢的事情,但我想我会提到这个惯例,因为它让其他人更容易阅读你的代码。


Off-topic 2: The overwhelming convention in JavaScript code is to use initial caps on function names only for constructor functions (like Person), and not on other kinds of functions (like Name). You're free to do whatever you like, of course, but I thought I'd mention the convention, as it makes it easier for other people to read your code.

值得注意的是:所有这些技术会导致每一个 Person 对象拥有其访问者函数的拥有副本。如果会有很多这些对象,那可能是内存问题。如果只有一些,那很好。

Worth noting: All of these techniques result in every single Person object having its own copy of the accessor function. If there are going to be a lot of these objects, that could be a memory issue. If there are only going to be a few, that's fine.

这篇关于强迫上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆