希望有人能够帮助我分解来自Crockford的JS Good Parts中的代码片段:
Function.method('new', function ( ) {
// Create a new object that inherits from the
// constructor's prototype.
var that = Object.create(this.prototype);
// Invoke the constructor, binding –this- to
// the new object.
var other = this.apply(that, arguments);
// If its return value isn't an object,
// substitute the new object.
return (typeof other === 'object' && other) || that;
});
我不太理解的是当他使用apply调用模式来创建一个对象时:
var other = this.apply(that, arguments);
执行this函数将如何创建新对象?
如果该函数是:
var f = function (name) {
this.name = "name";
};
如何进行函数调用:
var myF = f.new("my name");
创建对象?
this
将引用什么。 - Felix KlingFunction.method
是什么?它有什么作用? - Joseph