简体   繁体   English

更改私人课程方法

[英]Change private class methods

I am attempting to change the behavior of a jquery plugin without actually changing the source. 我试图在不实际更改源的情况下更改jquery插件的行为。 For the purposes of this question, I constructed a simple example that illustrates my problem. 出于这个问题的目的,我构造了一个简单的示例来说明我的问题。 If a have script file that attaches a class instance generator to a global variable like this: 如果具有将类实例生成器附加到全局变量的脚本文件,如下所示:

(function(){

window.newMyClass = function(){
    return new myclass();
}

function myclass(){
    var privateMethod = function(){
        return "private";
    }
    this.publicMethod = function(){
        return privateMethod();
    }
}
})()

If I then get new instance of myclass with var instance = window.newMyClass() , is there any way to override the behavior of privateMethod on instance , such that instance.publicMethod() would call my overridden function? 如果我再拿到的MyClass新实例var instance = window.newMyClass()有没有办法覆盖的行为privateMethodinstance ,这样instance.publicMethod()会叫我重写的功能? I was thinking I could subclass myclass, but since the myclass constructor is scoped to the immediately invoked function expression, I don't know how to do that. 我当时以为我可以继承myclass的子类,但是由于myclass构造函数的作用域是立即调用的函数表达式,因此我不知道该怎么做。

Is it better just to change the plugin source? 仅更改插件源更好吗? The problem with that is I'd have to host it myself instead of using a CDN, as well as re-implement the change every time an update is released. 这样做的问题是,我必须自己托管它,而不是使用CDN,并且每次发布更新时都要重新实现更改。

I don't know if I understood well this. 我不知道我是否很好理解这一点。 Probably not, because there is no mistery with that: 可能不是,因为那没有神秘感:

(function(){

window.newMyClass = function(){
    return new myclass()
}

function myclass(){
    var privateMethod = function(){
        return "private";
    }
    this.publicMethod = function(){
        return privateMethod();
    }
}
})();

var instance = window.newMyClass();

instance.publicMethod = function(){
        return "new method";
}

console.log(instance.publicMethod());

FIDDLE: http://jsfiddle.net/r9evbzd2/1/ 内容: http : //jsfiddle.net/r9evbzd2/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM