当 JavaScript 函数体中的 return 语句用作新对象的构造函数时(带有 'new' 关键字)有什么作用?
What is the effect of a return statement in the body of JavaScript function when it's used as a constructor for a new object(with 'new' keyword)?
通常return
简单的退出构造函数.但是,如果返回的值是一个 Object,则它被用作 new
表达式的值.
Usually return
simply exits the constructor. However, if the returned value is an Object, it is used as the new
expression's value.
考虑:
function f() {
this.x = 1;
return;
}
alert((new f()).x);
显示 1,但是
function f() {
this.x = 1;
return { x: 2};
}
alert((new f()).x);
显示 2.
这篇关于JS 构造函数中的返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!