JavaScript: вызов базовой функции из наследования прототипа - PullRequest
3 голосов
/ 25 января 2012
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; в лучшем случае небрежно.

Ответы [ 2 ]

3 голосов
/ 25 января 2012

Ваша текущая реализация имеет ошибку в 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 голос
/ 25 января 2012
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 для получения дополнительной информации.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...