我试图用这样的代码模拟 JavaScript 中的“new”运算符:
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
这正是'new'运算符所做的吗?有没有需要处理的案例?