var Model = function(client, collection) {
this.client = client;
this.collection = collection;
};
Model.prototype = {
constructor: Model,
getClient: function(callback) {
this.client.open(callback);
},
getCollection: function(callback) {
var self = this;
this.getClient(function(error, client) {
client.collection(self.collection, callback);
});
},
extend: function(key, fn) {
var self = this;
this[key] = function() {
fn.call(self); // A
};
}
};
我想要实现的是我可以“扩展”模型的功能。
var userModel = new Model(client, 'users');
userModel.extend('create', function(data, callback) {
this.getCollection(function(error, collection) {
collection.insert(data, { safe: true }, function(error, doc) {
callback.call(doc);
});
});
});
userModel.create({ fullName: 'Thomas Anderson' }, function() {
console.log(this); // { _id: '123456789012345678901234', fullName: 'Thomas Anderson' }
});
在A处,我必须进行参数传递,自定义“create”函数(数据和回调)的参数计数是可变的。
这是可能的,如果是这样的话?
答案 0 :(得分:3)
是的!您希望.apply
方法使用.call
方法。两者都应用上下文,但.apply
方法为参数采用数组 - 或者参数集合本身!
extend: function(key, fn) {
var self = this;
this[key] = function() {
fn.apply(self,arguments); // the special arguments variable is array-like
};
}
答案 1 :(得分:0)
this[key] = function() {
fn.apply(self, arguments);
};
答案 2 :(得分:0)
在@zetlen注释之后还有一件事,函数的范围(this)就是函数调用的最后一个点,在这种情况下:
userModel.create();
函数的“this”变量将是“userModel”。
因此,只要您使用“modelname.functionName()”调用它,就不需要传递self:
extend: function(key, f) {
this[key] = f;
}
(或只是)
userModel.someMethod = function() { ... };
然后当你调用modelkey时,你会将参数直接传递给函数,你将拥有你想要的范围。
var userModel = new Model(...);
userModel.extend('hi', function(arg) {
this === userModel;
arg === 42;
});
userModel.hi(42);
看看这个小提琴,看看它:http://jsfiddle.net/NcLQB/1/
但请注意,请记住,如果您取消模型的功能,它将不再具有范围,在您执行此操作的情况下,您最好继续像您的代码段一样。
var funct = userModel.hi;
funct(); // this === global!!!
// OR
// When the event is fired the scope isn't userModel
otherThing.on('someEvent', userModel.hi);
答案 3 :(得分:0)
除非您在原型中创建extend
方法并强制执行范围有任何隐藏的原因,否则您只需将方法分配给创建的实例:
var userModel = new Model(client, 'users');
userModel.create = function(data, callback) {
this.getCollection(function(error, collection) {
collection.insert(data, { safe: true }, function(error, doc) {
callback.call(doc);
});
});
});
它会更快,更清晰,你不必担心通过另一个函数传递参数。
通过封装范围(或上下文)并不总是一件好事,因为你限制了语言的动态。