2014-07-17 64 views
-1
Function.prototype.new = function () { 
    // Create a new object that inherits from the 
    // constructor's prototype. 
    var that = Object.create(this.prototype); 
    // Invoke the constructor, binding –this- to 
    // the new object. 
    var other = this.apply(that, arguments); 
    // If its return value isn't an object, 
    // substitute the new object. 
    return (typeof other === 'object' && other) || that; 
}); 

这是来自JavaScript的构造函数实例的一个替代实现:The Good Parts。 我的问题是为什么我们需要var other = ... 我们不能只返回变量吗?用Javascript查看构造函数调用的另一种方法

+0

您可能想要了解'&&'和'||'运算符的用途:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical_operators –

+0

谢谢为链接。它确实有帮助,但它没有回答我的问题。变量'that'引用新创建的对象。那么为什么还要检查'other'是什么类型呢?你可以直接返回'那个'吗? – Meyyappan

+1

我觉得你大部分都是因为标题误导而降低赞誉。你可能想要编辑标题,特别是你问的是什么 –

回答

1

我们不能只返回变量吗?

不,因为这不是new operator做什么:

如果构造函数没有明确地返回一个对象,[从样机继承]的 对象来代替。 (常 构造函数没有返回值,但他们可以选择这样做,如果 他们要覆盖正常的对象的创建过程。)

所以,如果调用构造函数返回一个other那是一个对象,我们需要返回它。

请注意,代码甚至是不正确的,因为返回的函数也应该视为对象(但typeof不会为其产生"object")。你也可以检查一下,或使用Object(other) === other trick。你也可能想看看Use of .apply() with 'new' operator. Is this possible?的一些答案。

+0

哦,男人,忘了所有关于适用新的伎俩。很好的回答 –

+0

然而,它并没有真正帮助我们理解“新”功能的细节:-) – Bergi

+1

不,但[此答案](http://stackoverflow.com/a/3658673/5056)确实 –

相关问题