javascript中构造函数是不需要有返回值的,但是如果其中添加了 return 语句结果会如何呢:
看如下代码:
示例1.
var Calculator = function () { return { add: function (x, y) { return x + y; } }; };
执行如下代码:
var calculator = new Calculator();
console.log(calculator); console.log(calculator.add(2, 2));运行结果:
示例2:
var Calculator = function () { this.addnew = function (x, y) { return x + y; } return 1; };
执行如下代码:
var calculator = new Calculator(); console.log(calculator); console.log(calculator.addnew(2, 2));
运行结果:
示例3:
var Calculator = function () { this.addnew = function (x, y) { return x + y; } return "1"; };
执行如下代码:
var calculator = new Calculator(); console.log(calculator); console.log(calculator.addnew(2, 2));
运行结果:
示例4:
var Calculator = function () { this.addnew = function (x, y) { return x + y; } return null; };
执行如下代码:
var calculator = new Calculator(); console.log(calculator); console.log(calculator.addnew(2, 2));
运行结果:
示例5:
var Calculator = function () { this.addnew = function (x, y) { return x + y; } return undefined; };
执行如下代码:
var calculator = new Calculator(); console.log(calculator); console.log(calculator.addnew(2, 2));
运行结果:
示例6:
var Calculator = function () { this.addnew = function (x, y) { return x + y; } return {}; };
执行如下代码:
var calculator = new Calculator(); console.log(calculator); console.log(calculator.addnew(2, 2));
运行结果:
举例7:
function test() { return function () { alert(1); } }
运行如下代码:
var ts = new test(); console.log(ts);
运行结果:
总结:如果return的是非对象(数字、字符串、布尔类型等)会忽而略返回值;如果return的是对象,则返回该对象。