问题描述
通常,在构造函数中,在函数中 this
绑定的对象在使用 new
前缀。但我想象,也有可能(我想我甚至在crockford的书中阅读)手动返回您自己的值。
如果你从构造函数返回一个值类型,你会得到不同的行为取决于是否使用 new
。这就是 String
的工作原理。在您的JavaScript控制台中查看此对象:
{
s:String(abc),
S:new String(abc)
}
Little s
包含字符串值,但大 S
包含字符串Object。
<$>
<$> p $ p>
function Foo(){
returnabc;
}
Foo.prototype.DoSomething = function(){
//与abc完全无关的
};
var a = Foo(); //字符串abc。没有DoSomething()方法。
var b = new Foo(); //具有DoSomething()方法的对象。不知道abc。
根据是否使用 new
得到完全不同的东西。
Typically, in a constructor function, the object that is bound to this
within the function is returned by it when it is called with the new
prefix. But I would imagine that it's also possible (I think I even read this in crockford's book) to manually return your own value. Are there any places where such a practice is useful?
If you return a value type from the constructor, you'll get different behavior depending on if new
was used. That's how String
works. Look at this object in your JavaScript console:
{
s: String("abc"),
S: new String("abc")
}
Little s
contains a string value, but big S
contains a string Object. A subtle difference, perhaps.
You could go way beyond that and use the same function for different purposes:
function Foo() {
return "abc";
}
Foo.prototype.DoSomething = function () {
// something completely unrelated to "abc"
};
var a = Foo(); // The string "abc". Does not have a DoSomething() method.
var b = new Foo(); // An Object with a DoSomething() method. Doesn't know about "abc".
Depending on whether new
was used, you'd get back something completely different.
这篇关于有什么理由在构造函数中手动`return'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!