有一个像这样的数组:
var k =[1,2];
k.push(3);
像这样重新定义推送:
function kPush(e){
this[this.length] = e * 2;
}
Object.defineProperty(k, 'push', {
get: function(){return kPush;}
});
并使用调用
k.push(4);
document.write(k);
给予:
var k =[1,2];
k.push(3);
function kPush(e){
this[this.length] = e * 2;
}
Object.defineProperty(k, 'push', {
get: function(){return kPush;}
});
k.push(4);
document.write(k);
给予:
1,2,3,8
一切都很好。现在我需要覆盖 splice
但它从未被调用。
Object.defineProperty(k, 'splice', {
get: function(){return kSplice;}
});
但是
console.debug(k.splice);
给我function splice() { [native code] }
。 <-- 它的 native ?但我已经覆盖了该属性!
如何覆盖splice
?
最佳答案
var k =[1,2];
k.push(3);
function kPush(e){
this[this.length] = e;
}
Object.defineProperty(k, 'push', {
get: function(){return kPush;}
});
Object.defineProperty(k, 'splice', {
get: function(){return function(){
console.log("Splice");
Array.prototype.splice.apply(this,arguments);
}}
});
k.push(4);
k.splice(1,1);
document.write(k);
关于javascript - 替换数组中的插入有效,但从未调用过 splice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42051856/