var ninja1 = new Ninja();//创建一个新的空对象,该对象作为this参数传递给构造函数 var ninja2 = new Ninja();//新构造的对象作为new运算符的返回值
assert(ninja1.skulk() === ninja1, "The 1st ninja is skulking"); assert(ninja2.skulk() === ninja2, "The 2nd ninja is skulking");
返回原始值的构造函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
functionNinja() { this.skulk = function () { returntrue; };
return 1; } assert(Ninja() === 1,//作为函数调用返回值是1 "Return value honored when not called as a constructor");
var ninja = new Ninja();//作为构造函数调用,返回值是一个对象
assert(typeof ninja === "object", "Object returned when called as a constructor"); assert(typeof ninja.skulk === "function", "ninja object has a skulk method");
使用apply和call方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
functionjuggle() { var result = 0; for (var n = 0; n < arguments.length; n++) { result += arguments[n]; } this.result = result; }