我对充当类的函数中的 return 语句感到困惑。请参阅下面的示例代码:
<html>
<body>
<script type="text/javascript">
function test() {
this.abc = 'def';
return 3;
}
var mytest = new test();
document.write(mytest + ', ' + (typeof mytest) + ', ' + mytest.abc);
</script>
</body>
</html>
输出的代码:[object Object], object, def.
这是我的问题。我在 test() 函数中写了“return 3”。调用 'new test()' 时是否忽略此语句?
谢谢。
最佳答案
当您使用 new
调用函数时,您将其作为构造函数调用,它会自动返回它构造的新对象。
您的 return 3;
语句被忽略。返回的是有效的:
{ abc:'def' }
...带有对 prototype
对象的隐式引用,在您的示例中它没有任何可枚举的属性,因为您没有给它任何属性。
如果你这样做了:
mytest instanceof test;
...它将评估为 true
。
如果你这样做了:
function test() {
this.abc = 'def';
}
test.prototype.ghi = 'jkl';
var mytest = new test();
...然后你可以这样做:
mytest.ghi;
...这将为您提供值 'jkl'
。
关于javascript - 作为类的函数中的 return 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4770070/