请考虑以下代码:
var f = function() { return 10; }
typeof f; // returns "function"
f(); // returns 10
var g = f;
g(); // returns 10, obviously
var h = new f;
h; // console evaluates to f - ????
h(); // Type error - called_non_callable
typeof h; // returns "object"
Run Code Online (Sandbox Code Playgroud)
那么,这里有什么?Chrome控制台似乎将其评估为f,但它不可调用."新"这样的功能意味着什么?现在如何与f相关?
顺便说一句,这两行看起来是等价的:
var h = new f;
var h = new f();
Run Code Online (Sandbox Code Playgroud)
那是怎么回事?
您困惑的根源在于 Chrome 在其控制台上表示对象的方式。
您的示例中的表达式在 Chrome 的控制台输出上new f()表示为“ f”,但这只是为了此特定控制台的“方便”,例如记录以下对象:
({constructor: function Foo(){}});
Run Code Online (Sandbox Code Playgroud)
将显示它表示为“ Foo”。基本上,控制台尝试找到您的对象是哪个构造函数的实例的表示。
因此,控制台向您显示f,但您没有记录该函数,new操作符生成一个继承自 的对象f.prototype。
10您正在从函数返回,但由于您使用 调用它new,并且返回类型是基本类型f.prototype,因此该值被丢弃,返回继承 form 的新创建的对象。
例如:
var F = function () { return 10; };
F.prototype.inherited = 'foo';
var h = new F(); // the 10 returned is ignored
h instanceof F; // true
h.inherited; // "foo"
Run Code Online (Sandbox Code Playgroud)
另一方面,如果从构造函数返回一个对象,则new操作符在场景后面创建的对象实例(并从构造函数的原型继承)将丢失,例如:
var F = function () { return {}; };
F.prototype.inherited = 'foo';
var h = new F(); // the empty object is returned
h instanceof F; // false
h.inherited; // undefined
Run Code Online (Sandbox Code Playgroud)
是的,new f;和new f();是完全等价的,尽管人们建议使用括号来使代码更加清晰。
| 归档时间: |
|
| 查看次数: |
1572 次 |
| 最近记录: |