我想知道是否有一种本地方法可以做到这一点:
Object.prototype.chain = function(f) { return f.call(this) }
function fun1() {
doSomethingWithObject(this)
return this
}
function fun2() {
doSomethingElse(this)
return this
}
someObject
.method1('something')
.method2()
.chain(checkSomething() ? fun1 : fun2)
.method3()
但我不想更改Object
的原型(prototype)。有没有一种方法可以在不修改 Objects
的原型(prototype)或我使用的其他构造函数(而不是其开发人员)的情况下执行此操作
编辑:
我觉得我解释得不是很好,所以让我们补充一些细节:
我想做的是使用一些我没有定义的 API。 someObject
定义如下,带有可链接的方法:
var someObject = {
method1: function(val) {
// do something
return this
},
method2: function() {
// do something
return this
},
method3: function() {
// do something
return this
}
}
现在假设我无法更改此代码,因为此对象来自库,所以我不想这样做。然后,假设我想为更多不同的对象链接方法和一些自定义函数(请参阅我的第一个片段)。最简单的做法是将 chain
方法附加到 Object.prototype
。
但我认为这可能会导致将来发生冲突。我正在寻找一种在不接触原型(prototype)的情况下做同样事情的方法。
最佳答案
老实说,我很惊讶没有答案。
有很多方法可以在本地引入链接。我喜欢使用 revealing module pattern .
所以我创建了一个基本模型(继续并将其放入您的 Firefox 控制台的 chrome 中)
var Dog = function(name) {
var self = this;
this.name = name;
var core = {
getName:function(){
return self.name;
}
};
this.movement = function(){ //this function will be exposed including its returned functions for chaining
console.log(self.name + " is getting restless... ");
var jump = function(){
console.log(self.name + " jumps around ");
return this //returns the movement scope
};
var run = function(){
console.log(self.name + " has decided to run");
return this //returns the movement scope
};
return {
jump:jump,
run:run
};
}
console.log("A Pup has been born, we shall call him... " + name);
return{
movement:self.movement //only .movement is exposed to the outside world
};
}
现在使用 var p = new Dog("doggyName");
现在,您可以链接函数。尝试:
p.movement().jump().run().jump().run();
您应该获得与每个函数对应的控制台记录文本。
通过在执行移动函数后返回 this 的范围,您公开了在该范围内返回的附加函数(请参阅代码中的注释)。然后可以将它们链接到当前函数的末尾,前提是它们在同一范围内。这允许您限定代码的特定部分。例如,对于这只狗,所有运动都限定在 self.movement
范围内,您可以将所有进食范围限定在 self.eat
等等
Read up on the revealing module pattern .尽管这不是唯一的方法。
关于javascript - 一种将自定义 JavaScript 函数添加到方法调用链中的 native 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30501325/