I tried to simulate the 'new' operator in JavaScript in a code like this:
Function.method('new', function ( ) {
var objPrototype = Object.create(this.prototype);
var instance = this.apply(objPrototype, arguments);
return instance;
});
However, in order to cover all the cases, the return statement should look like this:
return (typeof instance === 'object' && instance ) || objPrototype;
Now for the tests:
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
Is this exactly what the 'new' operator does? Is there any case left to cover?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…