带有原型的对象中的对象字面量,带有函数参数

Object literal in object with prototypes, with funtion parameters

我有一个对象,里面有一个函数和一个对象字面量:

function SomeThing() {
    var self = this;
    self.publicFunction = function() {...}

    self.choose = function(data) {
        var script = {
            one: self.one,
            two: self.two,
        };
        return (script[data.type])(data);
    };
};
SomeThing.prototype.one = function one(data) {
    console.log(this);
    this.publicFuntion();
    ...
};
...

我需要将一些参数传递给附加了原型的函数。但是当我这样做时 return ...(data) public里面的功能无法访问。

var some = new SomeThing();
some.choose(data); // data.type === 'one'
// -> undefined
// -> Cannot read property 'publicFunction' of undefined.

如何在原型中使用 public 函数或在对象字面量中传递参数?

您是在 script 对象而不是 SomeThing 实例上调用方法。使用 call 显式设置接收器

…choose = function(data) {
    var script = {
        one: self.one,
        two: self.two,
    };
    return script[data.type].call(self, data);
};

或者只是删除 script 对象并直接使用

…choose = function(data) {
    if (["one", "two"].includes(data.type))
        return self[data.type](data);
};