我对充当类的函数中的 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>
Run Code Online (Sandbox Code Playgroud)
代码输出:[object Object], object, def。
这是我的问题。我在 test() 函数中写了“return 3”。调用“new test()”时是否会忽略此语句?
谢谢。
当您使用 调用函数时new
,您将其作为构造函数调用,该构造函数会自动返回它构造的新对象。
您的return 3;
声明将被忽略。返回的内容实际上是:
{ abc:'def' }
Run Code Online (Sandbox Code Playgroud)
...使用对对象的隐式引用prototype
,在您的示例中,该对象没有任何可枚举属性,因为您没有给它任何属性。
如果你这样做:
mytest instanceof test;
Run Code Online (Sandbox Code Playgroud)
...它将评估为true
。
如果你这样做:
function test() {
this.abc = 'def';
}
test.prototype.ghi = 'jkl';
var mytest = new test();
Run Code Online (Sandbox Code Playgroud)
...然后你可以这样做:
mytest.ghi;
Run Code Online (Sandbox Code Playgroud)
...这会给你价值'jkl'
。