And*_*ius 6 javascript paradigms class instantiation
考虑:
function Panda() {
this.weight = 100;
return [1,2];
}
console.log(new Panda());
Run Code Online (Sandbox Code Playgroud)
当我们使用new
keyword(new Panda()
)实例化时,它将返回:[1,2]
没有return语句,它返回: { weight: 100 }
function Panda() {
this.weight = 100;
}
console.log(new Panda());
Run Code Online (Sandbox Code Playgroud)
使用返回语句,如:return "Hello"
,它返回{ weight: 100 }
function Panda() {
this.weight = 100;
return "Hello";
}
console.log(new Panda());
Run Code Online (Sandbox Code Playgroud)
为什么这样做?因为它必须是一个对象吗?