希望有人能帮我打破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);
如何执行此函数将如何创建新对象?
如果功能如下:
var f = function (name) {
this.name = "name";
};
如何致电:
var myF = f.new("my name");
创建对象?
答案 0 :(得分:5)
首先,请注意Function.method
isn't a built-in JS method。这是Crockford made up:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
因此,Function.method
方法调用基本上是这样做的:
Function.prototype.new = function() {
var that = Object.create(this.prototype);
var other = this.apply(that, arguments);
return (typeof other === 'object' && other) || that;
});
然后当你像
一样使用它时f.new("my name");
它这样做:
f.prototype
(实例)的对象。f
将该实例作为this
值传递。
name
属性设置为实例。f
的调用返回了某个对象,则返回该对象
否则,将返回在步骤1中创建的实例。