为什么这个扩展方法不起作用?

Why won't this extend method work?

function world_rat_head() {
    this.ext = function (obj) {
        if (obj instanceof Object) return $.extend(obj, this); 
    };
}

我希望结果是一个扩展对象。我该怎么做?

您不需要(obj instanceof Object)$.extend 如果您尝试扩展原语,将不执行任何操作。

另外,请注意 $.extend 的第一个参数是用来添加内容的。如果您打算让 $.extend 修改 this,那么 this 需要作为第一个参数;否则,它是正确的。

这应该有效,假设 this 是您要合并的对象 obj:

this.ext = function(obj) {
    return $.extend(obj, this);
}
// Test
var o = {a: 5};
console.log(this.ext(o));

如果它不起作用,请同时记录 objthis 并查看它是否符合您的预期。另外,确保 this 不是 window.