JavaScript:从原型继承调用基本函数

时间:2012-01-24 21:39:25

标签: javascript function call prototype base

var super_class = function(p) {
    this.p = p + 1;
    this.method = function(a, b) {
        // some code
    };
};

var base_class = function(o) {
    this.o = o;
    super_class.call(this, o);
    this.method = function(a, b) {
        // call super_class .method();
        // some code
    }
}

base_class.prototype = new super_class();

var bc = new base_class(0);
var v1 = bc.o; // 0
var v2 = bc.p; // 1

当名称和属性假设相同时,如何调用super_class method。如果我更改了名称,我只需从另一个函数中调用this.method(3, 4);。我正在为另一个扩展类创建一个扩展类,因此更改该函数的名称对我没有帮助。

此外,将函数存储在私有变量var pmethod = this.method;中充其量只是草率。

3 个答案:

答案 0 :(得分:3)

您当前的实施在super_class(this, o);处出错。要么用super_class.call(this, o)替换它,要么正确实现初始化方法:

// Basic super class method.
var Super_class = function(p) {
    this.init(p); // Call initializer
};

// Define prototype properties and methods
Super_class.prototype = {
    constructor: Super_class,
    init: function(p) { this.p = p + 1; },
    method: function(a, b) {
        console.log("Super class method, arguments: " + [a,b]);
    }
};

// Define base_class
var Base_class = function(o) {
    this.o = o;   // Initialize `o` property
    this.init(o); // Initialize p variable through the initializer
};
// Extend `Base_class` prototype with `method`.
Base_class.prototype.method = function(a, b) {
    // Call the method from the parent = Super_class.prototype.method
    this.constructor.prototype.method(a, b);
};

Base_class.prototype = new Super_class; // Set prototype to `super_class`.

var bc = new Base_class(0);
var v1 = bc.o; // 0
var v2 = bc.p; // 1
bc.method('Hi: ', [v1, v2]); // Prints "Super class method, arguments: Hi [0,1]"

或者,您也可以在Base_class本身推送Base_class的所有方法和/或创建对父类的引用:

// Define base_class
var Base_class = function(o) {
    var __super__ = this.constructor.prototype;
    this.o = o;   // Initialize `o` property
    this.init(o); // Initialize p variable through the initializer
    Base_class.prototype.method = function(a, b) {
        // Call the method from the parent = Super_class.prototype.method
        __super__.method(a, b);
    };
};

答案 1 :(得分:1)

var super_class = function(p) {
    this.p = p + 1;
    this.method = function(a, b) {
        // some code
    };
};

var base_class = function(o) {
    this.o = o;
    super_class(o); // remove "this"
    this.method = function(a, b) {
         // call base.method();
         // some code
    }
}

base_class.prototype = new super_class();

base_class.prototype.constructor = base_class;  //important: pointing the constructor back to the base class.

这是在JavaScript中完成的基本继承。如果你想获得一些奇特的东西,请使用

function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

有关详细信息,请参阅http://javascript.crockford.com/prototypal.html

答案 2 :(得分:0)

请查看此链接http://mckoss.com/jscript/object.htm

您将找到有关多态性和子类定义的信息。