希望有人能帮我分解 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;
});
我不明白的部分是当他使用应用调用模式创建对象时:
var other = this.apply(that, arguments);
如何执行this 函数来创建新对象?
如果函数将是:
var f = function (name) {
this.name = "name";
};
调用方式:
var myF = f.new("my name");
创建对象?
最佳答案
首先注意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
属性设置为实例。 - 此步骤不会创建任何新实例,该实例是在步骤 1 中创建的。
- 在这种情况下,这会将
- 如果对
f
的调用返回了某个对象,则返回该对象。
否则,返回在步骤 1 中创建的实例。
关于javascript - Crockford "new"方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32513148/