我的javascript源代码中存在一些设计模式错误

时间:2015-10-31 09:45:53

标签: javascript

我尝试运行此代码,但控制台显示此错误消息。

异常:TypeError:undefined不是对象(评估'Stack()。push')

我知道替代方法是使用原型来完成此代码,但我正在尝试研究这种模式。 请让我知道解决此错误。

var Stack = function() {
this.repository = [1];

debug('current this.repository: ' + this.repository);


function push(data) {
    debug('this: ' + this);
    debug('current this.repository: ' + this.repository);
    debug('after pushing data: ' + this.repository);
}

function pop() {
    if (!this.repository.length) {
        return null;
    }

    var result = this.repository[this.repository.length - 1];
    this.repository = this.repository.slice(0, this.repository.length - 1);
    debug('after poping data: ' + this.repository);

    return result;
}

};

Stack().push(9);
Stack().push(10);
Stack().pop();

1 个答案:

答案 0 :(得分:0)

您需要使用new进行构造函数调用。以及公共方法的一些任务。



var Stack = function () {
    this.repository = [1];
    document.write('current this.repository: ' + this.repository + '<br>');

    function push(data) {
        document.write('this: ' + this + '<br>');
        document.write('current this.repository: ' + this.repository + '<br>');
        this.repository.push(data); // was missing
        document.write('after pushing data: ' + this.repository + '<br>');
    }

    function pop() {
        if (!this.repository.length) {
            return null;
        }
        var result = this.repository[this.repository.length - 1];
        this.repository.slice(0, this.repository.length - 1); // works without assignment
        document.write('after poping data: ' + this.repository + '<br>');
        return result;
    }
    this.pop = pop;
    this.push = push;
};
var stack = new Stack();

document.write('stack.push(9) ' + stack.push(9) + '<br>');
document.write('stack.push(10) ' + stack.push(10) + '<br>');
document.write('stack.pop() ' + stack.pop() + '<br>');
&#13;
&#13;
&#13;

如果不使用new,则可以使用以下模式:

&#13;
&#13;
var Stack = {
    repository: [1],

    push: function (data) {
        document.write('this: ' + this + '<br>');
        document.write('current this.repository: ' + this.repository + '<br>');
        this.repository.push(data); // was missing
        document.write('after pushing data: ' + this.repository + '<br>');
    },

    pop: function () {
        if (!this.repository.length) {
            return null;
        }
        var result = this.repository[this.repository.length - 1];
        this.repository.slice(0, this.repository.length - 1);
        document.write('after poping data: ' + this.repository + '<br>');
        return result;
    }
};

document.write('Stack.push(9) ' + Stack.push(9) + '<br>');
document.write('Stack.push(10) ' + Stack.push(10) + '<br>');
document.write('Stack.pop() ' + Stack.pop() + '<br>');
&#13;
&#13;
&#13;

相关问题