首先我们都知道js中构造函数一般应该是这样的
function Super (a) {
this.a = a;
}
Super.prototype.sayHello = function() {
alert('hello world');
}
但如果在构造函数中 加入 return 会是什么结果呢
function Super (a) {
this.a = a;
return {a: 2};
}
Super.prototype.sayHello = function() {
alert('hello world');
}
new 这个构造函数会返回什么?
Object {a: 2}
为什么会这样?我们的构造函数和原型上的方法呢?别急 我们再来 列出集中情况
//直接 return
function A(){
return;
}
//返回 数字类型
function B(){
return 123;
}
//返回 string类型
function C(){
return "abcdef";
}
//返回 数组
function D(){
return ["aaa", "bbb"];
}
//返回 对象
function E(){
return {a: 2};
}
//返回 包装类型
function F(){
return new Number(123);
}
结果分别是
A {}
B {}
C {}
["aaa", "bbb"]
Object {a: 2}
Number {[[PrimitiveValue]]: 123}
A {}
我们可以看出 return 基本类型 会返回一个空对象
而返回对象类型 则会返回这对象
与我们常用的那个构造函数相结合
function Super (a) {
this.a = a;
return 123;
}
Super.prototype.sayHello = function() {
alert('hello world');
}
function Super_ (a) {
this.a = a;
return {a: 2};
}
Super_.prototype.sayHello = function() {
alert('hello world');
}
分别new Super(1); new Super_(1);
结果是
Super {a: 1} 具有原型方法sayHello
Object {a: 2}
好了现在我们总结下 在构造函数中 return 基本类型 不会影响
构造函数的值而 return 对象类型 则会替代构造函数返回该对象