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

Can access an attribute of my object but not a function

本文关键字:访问 但不能 属性 函数 对象      更新时间:2023-09-26

我必须弄清楚,如何开发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成功进入控制台。但是警报永远不会被调用。我不明白,为什么不呢?我应该改变什么?

该对象初始化式中间的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;

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

  actions: [{
        title: 'This is great',
        do_this: 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();
我希望你得到了答案。由于

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