Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 扩展原型方法_Javascript_Prototype - Fatal编程技术网

Javascript 扩展原型方法

Javascript 扩展原型方法,javascript,prototype,Javascript,Prototype,现在我有了一个原型,比如: function A() {} A.prototype.run = function () { console.log('run 1'); }; 考虑到我无法更改A所在的任何位置(无法控制源)。我想扩展方法run。不仅要记录运行1,还要记录运行2。我尝试了几种不同的方法,但都不起作用 A.prototype.run = function () { this.run.call(this); console.log('run 2'); }

现在我有了一个原型,比如:

function A() {}

A.prototype.run =  function () {
    console.log('run 1');
};
考虑到我无法更改A所在的任何位置(无法控制源)。我想扩展方法
run
。不仅要记录
运行1
,还要记录
运行2
。我尝试了几种不同的方法,但都不起作用

A.prototype.run = function () {
    this.run.call(this);
    console.log('run 2');
}


有人能解决这个问题吗?我宁愿不要复制方法
run
中的内容。谢谢

您可以覆盖
run
方法,将对它的引用保存为该方法

(function (orig) {

    A.prototype.run = function () {
        orig.apply(this, arguments);

        console.log('run 2');
    }

}(A.prototype.run));
这与第一次尝试类似,但保留了
run
的第一个值,因此您可以在尝试时有效地执行
This.run.call(This)

A.prototype._run = A.prototype.run;
A.prototype.run = function () {
    this._run.call(this);
    console.log('run 2');
}
A.prototype._run = A.prototype.run;
A.prototype.run = function () {
    this._run.call(this);
    console.log('run 2');
}