是否可以将回调附加到本机JS函数。例如,当调用Array.prototype.push('d')
时,我想触发另一个函数。可能吗?
更新:
function Dummy() {};
Dummy.prototype = Array.prototype;
var arrObj = new Dummy();
var domElement = 'itemsList';
arrObj = ['werew', 'werewr', '234324'];
(function(native) {
arrObj.push = function() {
native.apply(this, arguments);
arrObj.render(domElement);
};
})(arrObj.push);
arrObj.addItem = function(item) {
this.push(item); //Uncaught TypeError: this.push is not a function
this.render(domElement);
return this;
}
答案 0 :(得分:3)
你可以用自己的功能劫持它:
(function(native) {
Array.prototype.push = function() {
native.apply(this, arguments); // Redirect call to the native function
// Do something here
};
})(Array.prototype.push);