【问题标题】:Instance method inheritance实例方法继承
【发布时间】:2017-06-23 00:22:50
【问题描述】:

有没有办法为实例的方法声明继承。

//SOME CLASS
class SomeClass{
    someMethod{
        //SOMETHING HAPPENS
    }
}
function myComponent(){
    this.subcomponents={
        popup:function(){
            //SOMETHING HAPPENS
        }
    }
    this.init=()=>{
        //NEW INSTANCE OF SUBCOMPONENT POPUP
        var popup = new this.subcomponents.popup();
        //DESIRED RESULT WOULD BE ABLE TO CALL
        popup.someMethod();
    }
}
//myComponent inherits someMethod()
myComponent.prototype = new SomeClass();
//IS THERE ANYWAY TO ASSIGN INHERITANCE TO SUBMETHODS OF AN INSTANCE 
myComponent.subcomponents.popup.prototype = new SomeClass();

期望的输出是拥有 popup 方法的新实例并继承 SomeClass,这样我就可以调用 popup.someMethod()

问题:如何分配popup 方法,继承SomeClass 以便调用popup.someMethod()

【问题讨论】:

    标签: javascript object inheritance


    【解决方案1】:

    如果我理解正确,您想以某种方式在 SomeClass 中使用 someMethod 函数并将其应用于弹出窗口。为了做到这一点,您不需要弄乱原型链和继承。

    SomeClass.prototype.someMethod.call(popup, arguments)
    

    这将采用 someMethod,并将 'this' 的值更改为弹出并使用您提供的任何参数执行它

    【讨论】:

    • 我根本不想这样做。我实际上正在尝试做popup.someMethod()popup.whatevermethodfromtheinheritedclass()
    • 既然你用的是 es6,那你为什么不把 popup 做成一个单独的类来扩展 SomeClass 呢?
    • 我的意思是 ES5 或 ES6 完全相同...但是目前我知道的唯一方法是创建单独的类。很多时候,类是如此之小并且仅相对于父类,它们应该作为父类的子组件或子类进行管理,所以这就是我正在寻找的方法.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 2020-07-29
    • 1970-01-01
    相关资源
    最近更新 更多