簡體   English   中英

如何在 JavaScript 中更改構造函數內的函數?

[英]How to change function inside constructor in JavaScript?

我需要編輯位於構造函數內部的函數。 例子:

some.thing = function() {
    this.somefn = function() { // this is the function that I need to fix
        ...
    }
}

但是不僅應該為單個對象( new obj = some.thing(); )編輯函數,還應該為該構造函數創建的任何對象編輯函數。

那么有沒有辦法編輯這樣的內部功能呢?

解決方案似乎有點太明顯了,所以我想知道問題是否在於您無法訪問原始代碼,而您需要一個更動態的解決方案。

如果是這樣,一種選擇可能是用您自己的構造函數覆蓋構造函數,並讓它調用原始構造函數,然后更新對象。


原始代碼:

some.thing = function() {
    this.somefn = function() { // this is the function that I need to fix
        ...
    }
}

您的代碼:

       // cache a reference to the original constructor
var _thing = some.thing;

               // your constructor
some.thing = function() {

             // invoke the original constructor on the new object.
    _thing.apply(this, arguments);

    this.somefn = function() { /*your updated function*/ };
};

        // maintain inheritance
some.thing.prototype = Object.create(some.thing.prototype);

  // make an instance
var theThing = new some.thing();

現在您獲得了原始構造函數和原型鏈的好處,但是您將自己的函數注入到正在創建的對象上。

唯一的麻煩可能是您替換的原始函數可能會特殊使用原始構造函數的變量范圍。 如果是這樣,那就有問題需要解決了。

在調用您的方法之前,可以保留並調用您覆蓋的原始方法。 不確定這種情況是否需要。

這是一個基於原型的解決方案:

var Something = function () {
    this.f = function () {
       console.log("Something");
    };    
};
var Old = Something;
var Something = function () {
    Old.apply(this);
    this.f = function () {
        console.log("New");
    };
};
Something.prototype = new Old();

var s = new Something();
s.f(); // prints "New"

我完全知道你的需要,因為上周我通過了它。 我剛剛在 javascript 中實現了一個完整的繼承模型,據我所知,我在覆蓋構造函數和在子類初始化時調用父類的 ctor 時遇到了問題。

所以我只是通過修改我的設計中的一些點來解決這個問題,現在它就像一個魅力! (類似於 C# 但在 Javascript 中)

順便說一句,我不建議您以這種方式更改方法內容,但這里有一種方法可以做到這一點(我自己沒有這樣做,而且我不建議這樣做。還有很多其他方法,但是這是最簡單的):

var test = function() { /*InjectionPlace*/ };

eval("var newTest = " + test.toString().replace(
     "/*InjectionPlace*/", 
     "var i = 10; alert(i);"
));

test();

newTest();

干杯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM