繁体   English   中英

在功能内改变原型

[英]Change prototype within function

我的javascript代码有问题。 我有这个原型,我想以一种你可以添加'中间件'或你如何调用它的方式。 (如在ExpressJS中, app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(...)

var Server = function(...){
    ...
};
Server.prototype.log = function(data){
    console.log(data);
};
console.log(typeof(Server.prototype.log)); //function

因此我将其更改为通过调用函数添加函数的方式,以便稍后实现类似_add('fnName', loadUser, function(...))

var Server = function(...){
    ...
};
_add = function(fnName, fn){
    Server.prototype.fnName = fn;
    console.log(typeof(Server.prototype.fnName)); //always function
};
_add('log', function(data){
    console.log(data);
});
console.log(typeof(Server.prototype.log)); //undefined

但是这不起作用。 原型没有改变。

我不想像在ExpressJS中那样(你添加到一个实例,而不是原型),因为将为每个用户创建一个Server对象(与socket.io结合使用),因此向对象添加函数将更多开销而不是添加到其功能在所有情况下都可用的原型。

您需要使用Server.prototype[fnName] ,因为Server.prototype.fnName在Server的原型上定义了一个名为fnName的函数。

所以在你的例子中:

console.log(typeof(Server.prototype.log));   // undefined
console.log(typeof(Server.prototype.fnName)); // function

码:

var Server = function(...){
  ...
};

_add = function(fnName, fn){
  Server.prototype[fnName] = fn;
  console.log(typeof(Server.prototype[fnName])); //always function
};

_add('log', function(data){
  console.log(data);
});

console.log(typeof(Server.prototype.log)); // function

请参阅此片段

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM