可以访问我的对象的属性但不能访问函数

时间:2015-08-01 20:40:16

标签: javascript

我必须弄明白,如何以正确的方式开发oop-javascript。我读了很多关于prototypes的内容,但互联网向我解释,如果我多次创建一个对象,我只需要它。但我的SuperInterface只存在一次。所以我把它创建为一个对象:

var SuperInterface = {
    superaction: function () {
        alert(1);
    },
    actions: [{
        title: 'This is great',
        do_this: this.superaction
    }],
    init: function () {
        console.log(this.actions[0].title);
        this.actions[0].do_this();
    }
};
SuperInterface.init();

运行init()会将title成功置于控制台。但是警报从未被调用过。我不明白,为什么不呢?我应该改变什么?

3 个答案:

答案 0 :(得分:6)

该对象初始值设定项中间的this是对“正在构建”的对象的引用。由于该对象尚不存在,因此无法在初始化期间获得此类引用,也不会使用this引用它。所以你真的无法初始化这样的属性。但是,您可以将其拆分为单独的声明:

var SuperInterface = {
    superaction: function () {
        alert(1);
    },
    actions: [{
        title: 'This is great',
        do_this: null;
    }],
    init: function () {
        console.log(this.actions[0].title);
        this.actions[0].do_this();
    }
};
SuperInterface.actions[0].do_this = SuperInterface.superaction;

答案 1 :(得分:2)

如果您调试此代码,您会发现SuperInterface.actions[0].do_thisundefined 原因很明显。在评估代码时。

  actions: [{
        title: 'This is great',
        do_this: this.superaction
    }]

this.superaction,这里this指向窗口对象。

并且在这个窗口中对象superaction没有退出..

要最终完成这项工作,您需要

var SuperInterface = {
    superaction: function () {
        alert(1);
    },
    actions: [{
        title: 'This is great',
        do_this: null
    }],
    init: function () {
        console.log(this.actions[0].title);
        this.actions[0].do_this();
    }
};
SuperInterface.actions[0].do_this = SuperInterface.superaction;
SuperInterface.init();

我希望你能得到答案。 感谢

答案 2 :(得分:0)



var SuperInterface = {
    superaction: function () {
        alert(1);
    },
    actions: [{
        title: 'This is great',
        do_this: function() {
          return SuperInterface.superaction();
        }
    }],
    init: function () {
        console.log(this.actions[0].title);
        this.actions[0].do_this();
    }
};
SuperInterface.init();




在您的情况下,

this引用数组actions中的文字对象 - 它不包含方法superaction