`new function()` 带有小写字母“f";在 JavaScript 中 [英] `new function()` with lower case "f" in JavaScript

查看:24
本文介绍了`new function()` 带有小写字母“f";在 JavaScript 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的同事一直在使用带有小写字母f"的new function()"来定义 JavaScript 中的新对象.它似乎在所有主要浏览器中都运行良好,而且在隐藏私有变量方面似乎也相当有效.举个例子:

My colleague has been using "new function()" with a lower case "f" to define new objects in JavaScript. It seems to work well in all major browsers and it also seems to be fairly effective at hiding private variables. Here's an example:

    var someObj = new function () {
        var inner = 'some value';
        this.foo = 'blah';

        this.get_inner = function () {
            return inner;
        };

        this.set_inner = function (s) {
            inner = s;
        };
    };

一旦使用this",它就会成为 someObj 的公共属性.所以 someObj.foo, someObj.get_inner() 和 someObj.set_inner() 都是公开的.此外,set_inner() 和 get_inner() 是特权方法,因此它们可以通过闭包访问内部".

As soon as "this" is used, it becomes a public property of someObj. So someObj.foo, someObj.get_inner() and someObj.set_inner() are all available publicly. In addition, set_inner() and get_inner() are privileged methods, so they have access to "inner" through closures.

但是,我在任何地方都没有看到任何对这种技术的引用.甚至 Douglas Crockford 的 JSLint 也抱怨它:

However, I haven't seen any reference to this technique anywhere. Even Douglas Crockford's JSLint complains about it:

  • 奇怪的结构.删除新"

我们正在生产中使用这种技术,它似乎运行良好,但我有点担心它,因为它没有任何记录.有谁知道这是否是一种有效的技术?

We're using this technique in production and it seems to be working well, but I'm a bit anxious about it because it's not documented anywhere. Does anyone know if this is a valid technique?

推荐答案

我以前见过这种技术,它是有效的,您正在使用函数表达式,就像它是 构造函数.

I've seen that technique before, it's valid, you are using a function expression as if it were a Constructor Function.

但是恕我直言,您可以使用自动调用函数表达式实现相同的目的,我真的不明白以这种方式使用 new 运算符的意义:

But IMHO, you can achieve the same with an auto-invoking function expression, I don't really see the point of using the new operator in that way:

var someObj = (function () {
    var instance = {},
        inner = 'some value';

    instance.foo = 'blah';

    instance.get_inner = function () {
        return inner;
    };

    instance.set_inner = function (s) {
        inner = s;
    };

    return instance;
})();

new 操作符的目的是创建新的对象实例,设置[[Prototype]] 内部属性,你可以看到这是如何通过[Construct] 内部属性.

The purpose of the new operator is to create new object instances, setting up the [[Prototype]] internal property, you can see how this is made by the [Construct] internal property.

上面的代码将产生等效的结果.

The above code will produce an equivalent result.

这篇关于`new function()` 带有小写字母“f";在 JavaScript 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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