Javascript ООП наследование не работает - PullRequest
2 голосов
/ 25 января 2012

Итак, я пишу что-то, используя augment для наследования, и по какой-то причине я могу запустить this.setButtons(type) и console.log(this.buttons) в этом методе, но когда я запускаю свой this.getButtons(), он возвращается как неопределенный, хотя getButtons просто возвращает this.buttons. Любая помощь будет с благодарностью. Я опубликую весь код, который у меня есть, потому что, возможно, я не наследую должным образом. Заранее спасибо.

var ContextMixin = function () {};
ContextMixin.prototype = {
    createElements: function (el, mode, type) {
        var m;
        if (mode == 'exact') {
            $("#" + el).append("<ul id='contextmenu'>");
        } else {
            $(el).each(function () {
                m = $(this).append("<ul id='contextmenu'>");
            });
            $('body').append(m);
        }
        $("#contextmenu").css({
            'position': 'absolute',
            top: 13,
            left: 13
        });
        var new_buttons = this.getButtons();
        $.each(this.buttons['buttons'], function () {
            m.append("<li id='" + this + "'>" + this + "</li>");
        });
    },
    attachEvents: function () {
        functions = this.getFunctions(type);
        buttons = this.getButtons();
        for (index in buttons['buttons']) {
            addEvent(buttons['buttons'][index], this.functions[index][0], this.functions[index][1]);
        };
    },
    setFunctions: function (type) {
        var callback = {
            success: function (msg) {
                this.functions = msg;
            },
            failure: function () {
                alert('Error getting functions')
            }
        };
        $.ajax({
            type: 'GET',
            url: 'function_list.php?type=' + type,
            success: function (msg) {
                this.functions = msg;
            }
        });
    },
    getFunctions: function () {
        return this.functions;
    },
    setType: function (value) {
        this.type = value;
    },
    getType: function () {
        return this.type;
    },
    setButtons: function (type) {
        $.ajax({
            type: 'GET',
            url: 'button_list.php?type=' + type,
            success: function (reply) {
                this.buttons = reply;
            }
        });
    },
    getButtons: function () {
        return this.buttons;
    }
}

function createMenu(el, type, mode) {
    this.setButtons(type);
    this.setFunctions(type);
    this.createElements(el, mode, type);
}

augment(createMenu, ContextMixin);

function augment(receivingClass, givingClass) {
    if (arguments[2]) { //Only give certain methods.
        for (var i = 2, len = arguments.length; i < len; i++) {
            receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
        }
    } else { //Give all methods
        for (methodName in givingClass.prototype) {
            if (!receivingClass.prototype[methodName]) {
                receivingClass.prototype[methodName] = givingClass.prototype[methodName];
            }
        }
    }
}

Ответы [ 3 ]

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

Потому что this в обратном вызове AJAX-запроса не является вашим объектом.

Вот обычное исправление ...

setButtons: function(type) {
    var self = this;  // keep a reference to this
    $.ajax({
        type: 'GET', 
        url: 'button_list.php?type=' + type,
        success: function(reply) {
            self.buttons = reply; // use the reference here
        }
    });
},

... но лучше исправить этоиспользуйте свойство context: запроса $.ajax ...

setButtons: function(type) {
    $.ajax({
        type: 'GET', 
        context: this,  // set the context of the callback functions
        url: 'button_list.php?type=' + type,
        success: function(reply) {
            this.buttons = reply;
        }
    });
},
0 голосов
/ 25 января 2012

Если вы измените

ContextMixin.prototype = {
createElements

до

ContextMixin.prototype.createElements

должно работать.

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

this - это не то, что вы думаете в обратном вызове ajax - вместо того, чтобы быть вашим текущим объектом, это на самом деле глобальный объект объект XHR.Все, что делает ваш обратный вызов, это помещает свойство buttons в объект xhr.

Вам нужно сохранить this до запуска вашей функции:

setButtons: function(type) {
    var self = this;
    $.ajax({
        type: 'GET', 
        url: 'button_list.php?type=' + type,
        success: function(reply) {
            alert(reply);
            self.buttons = reply;
        }
    });
},
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...