将非继承函数添加到继承的类 - Javascript

时间:2014-02-02 04:36:47

标签: javascript jquery inheritance

我是Javascript中面向对象编程的新手。昨天我在javascript中了解了prototypeprototype.constructor以及他们如何在Javascript继承中发挥作用。

我已经创建了一个javascript函数,继承自父函数之一。但我希望这个孩子的一些方法不被其子函数继承。

即,

function A //parent
|
|`callA()
 `makeA()

这是主要的父类。

function B //child of A
|
|` callB() //can be inherited
|` makeB() //cannot be inherited
|` callA() //inherited
 ` makeA() //inherited

B是我想写的子函数。

function C //child of B
|
|` callC();
|` makeC();
|` callB();
|` callA();
 ` makeA();

我的写作方式如下:

function A(){}
A.prototype.callA = function()
{
    alert('CallA');
}
A.prototype.makeA = function()
{
    alert('makeA');
}

function B(){
    function makeB(){    //This is not working I am not able to call makeB with B's object
        alert('makeB'); 
    }   
}
B.prototype = new A();
B.prototype.constructor = B;
B.prototype.callB = function()
{
    alert('callB');
}
function C(){}
C.prototype = new C();
C.prototype.constructor = C;
C.prototype.callC = function()
{
    alert('callC');
}
C.prototype.makeC = function()
{
    alert('makeC');
}

$(document).ready(function(){
    var b = new B();
    var c = new C();
    $(document).click(function(){
        c.callB();
        c.callC();
        b.callB();
        b.makeB(); //not being called
    });
});

如何在JS继承中执行此部分。派生对象的私有函数。

1 个答案:

答案 0 :(得分:1)

您可以做的一件事是将makeB方法作为B构造函数的一部分添加到您的实例中,而不是将其放在将从C继承的原型中:

function B(){
   this.makeB = function(){
     //..
   };
}

但是,要使其工作,您需要使用Object.createe直接从父原型继承,而不是从父类的实例继承:

B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;

IE8中不支持Object.create,因此您可能需要找到它的垫片。

http://kangax.github.io/es5-compat-table/#Object.create


那就是说,我冒险说我所建议的可能不是解决问题的最佳方法。

第一种选择是将这些隐藏的方法公之于众。你确定你想要隐藏它们吗?

第二种方法是简单地为私有方法使用静态函数:

function makeB(obj){
    obj.callB();
}