我试图在这样的代码中模拟 JavaScript 中的“新”运算符:
Function.method('new', function ( ) {
var objPrototype = Object.create(this.prototype);
var instance = this.apply(objPrototype, arguments);
return instance;
});
但是,为了涵盖所有情况,return 语句应如下所示:
return (typeof instance === 'object' && instance ) || objPrototype;
现在进行测试:
var SomeClass = function (param1, param2) {
this.param1 = param1;
this.param2 = param2;
};
var test1 = String.new('test1'); //in this case, the "instance" variable is an object
var test2 = SomeClass.new('test1', 'test2'); // in this case, the "instance" variable is undefined
这正是“新”运营商所做的吗?有没有要处理的案子?