Why can't I save an object's methods as properties of another object literal

雨燕双飞 提交于 2019-12-11 15:25:35

问题


The code below is used to note some methods to run in particular circumstances so they can be called using a simpler syntax.

var callbacks = {alter: SPZ.sequenceEditor.saveAndLoadPuzzle,
                 copy: SPZ.sequenceEditor.saveAsCopyAndLoadPuzzle,
           justSave:SPZ.sequenceEditor.saveAndLoadPuzzle};

But the code keeps returning an empty object. I've checked with console.log that the methods are defined. I've also tried changing the names, invoking an empty object and then adding the properties as eg callbacks.alter, and tried other changes that shouldn't matter.

Why won't this work?

Demo

error is on line 238 of puzzle.js


回答1:


What exactly is the problem? Will the properties be undefined or the calls just not work correctly?

If the latter, the problem is most likely that when calling the methods, this will no longer refer to SPZ.sequenceEditor, but your callbacks object; to solve this problem, use the helper function bind() (as defined by several frameworks) or wrap the calls yourself:

var callbacks = {
    alter: function() {
        return SPZ.sequenceEditor.saveAndLoadPuzzle.apply(
            SPZ.sequenceEditor, arguments);
    },
    copy: function() {
        return SPZ.sequenceEditor.saveAsCopyAndLoadPuzzle.apply(
            SPZ.sequenceEditor, arguments);
    },
    justSave: function() {
        return SPZ.sequenceEditor.saveAndLoadPuzzle.apply(
            SPZ.sequenceEditor, arguments);
    }
};

The apply() is only necessary if the methods take arguments. See details at MDC.



来源:https://stackoverflow.com/questions/1816846/why-cant-i-save-an-objects-methods-as-properties-of-another-object-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!