gpt4 book ai didi

javascript - 扩展函数返回的属性?

转载 作者:行者123 更新时间:2023-11-30 17:27:26 24 4
gpt4 key购买 nike

我是 JS 初学者。我在我的 Backbone 模型上定义了一个函数,如下所示。

myFunction: function () {
return {
firstAttr: this.model.get('value-attribute')
};
}

我可以使用 this.myFunction

从代码的其他地方,我想扩展 this.myFunction 以返回另一个属性。换句话说,我希望它返回一个具有两个属性的字典:{ firstAttr: 'something', secondAttr: true }

我该怎么做?

我试过:

this.myFunction().secondAttr = true;

但我知道这样做是错误的。

最佳答案

假设你的模型原型(prototype)看起来像

var MyModel = Backbone.Model.extend({
myFunction: function () {
return {
// I assume you work directly on a model
// the principle would be the same with a wrapper object
firstAttr: this.get('value-attribute')
};
}
});

您可以像这样逐个模型地屏蔽您的方法:

var m = new MyModel({'value-attribute': 'attr, the first'});
console.log(m.myFunction());

m.myFunction = function () {
var res = MyModel.prototype.myFunction.call(this);
res.secondAttr = true;
return res;
};
console.log(m.myFunction());

参见 http://jsfiddle.net/V8zt2/演示

或者动态修改原型(prototype)以改变所有实例:

var f = MyModel.prototype.myFunction;
MyModel.prototype.myFunction = function () {
var res = f.call(this);
res.secondAttr = true;
return res;
};

var m = new MyModel({'value-attribute': 'attr, the first'});
console.log(m.myFunction());

http://jsfiddle.net/V8zt2/1/

关于javascript - 扩展函数返回的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23933177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com