为什么我不能将对象的方法另存为另一个对象文字的属性 [英] Why can't I save an object's methods as properties of another object literal

查看:79
本文介绍了为什么我不能将对象的方法另存为另一个对象文字的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码用于记录某些在特定情况下运行的方法,以便可以使用更简单的语法对其进行调用.

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};

但是代码不断返回一个空对象.我已经用console.log检查了方法的定义.我还尝试过更改名称,调用一个空对象,然后将属性添加为callbacks.alter等,并尝试了其他无关紧要的更改.

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.

为什么这行不通?

演示

puzzle.js的第238行出现错误

error is on line 238 of puzzle.js

推荐答案

究竟是什么问题?属性是undefined还是调用无法正常工作?

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

如果是后者,则问题很可能是在调用方法时,this将不再引用SPZ.sequenceEditor,而是您的callbacks对象.要解决此问题,请使用辅助函数bind()(由多个框架定义)或自行包装调用:

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);
    }
};

仅当方法带有参数时,才需要apply().请参见 MDC .

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

这篇关于为什么我不能将对象的方法另存为另一个对象文字的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆