我已将方法的名称存储在列表中。
var list = ['fn1', 'fn2', 'fn3', 'fn4'];
我动态地使用一些标准选择方法。这些方法是使用'prototype
MyObj.prototype.selectfn = function(criteria) {
var fn = list[sel];
this[fn].call(this, arg1);
}
MyObj.prototype.fn1 = function(args) { // do something }
MyObj.prototype.fn2 = function(args) { // do something}
等等。问题出在所选的“fn”函数中,this
变量显示为全局对象,即使我使用call()
我阅读了mozilla文档,但我无法理解为什么会这样,有人可以帮忙吗?
它有帮助,我的环境是node.js 0.10.12。
编辑:提供正确的示例代码有点困难,因为我的代码涉及很多地方的回调,但我会试着澄清。
假设有两个文件User.js
和Helper.js
。
User.js
var m, h;
var Helper = require('./Helper');
function init() {
// to simplify, assume the `this` here refers to `User`
h = new Helper(this);
}
function doSomething() {
// pass some criteria string
h.selectfn(criteria);
}
Helper.js
var Helper = module.exports = function(user) {
this.user = user;
}
Helper.prototype.selectfn = function(criteria) {
// based on some criteria string, choose the function name from "list" array
// here, the string "sel" holds the selected function name
var fn = list[sel];
this[fn].call(this.user, arg1);
// if I print to console, `this.user` is correct over here, but inside the function it shows as undefined
}
Helper.prototype.fn1 = function(args) {
// Here, I talk to databases, so I have callbacks. Say, on a callback, the user property is to be updated. This is why I want to use `call()` so that the `this` refers to `User` and can be updated.
// For example, if we want to update the "last-seen" date.
this.lastseen = new Date();
}
希望这个小例子让它更清晰。
答案 0 :(得分:0)
call()的第一个参数是你的函数上下文“this”
例如:
var someObject = {
withAFunction: function(text) { alert('hello ' + text); }
};
var testFunction = function(text) {
this.withAFunction(text);
};
testFunction.call(someObject, 'world');
答案 1 :(得分:0)
我尝试检查您的代码:
var list = ['fn1', 'fn2', 'fn3', 'fn4'];
//MyObj is copy of Object?
var MyObj = Object;
//or a preudoclass:
//var MyObj = function(){};
//inside this function you use sel and arg1 that seems undefined and use like arguments criteria that seems useless
MyObj.prototype.selectfn = function(sel,arg1) {
var fn = list[sel];
this[fn].call(this, arg1); // this is MyObj istance.
MyObj.prototype.fn1 = function(args) { console.log("fn1", args);/* do something */ }
MyObj.prototype.fn2 = function(args) { console.log("fn2",args); /* do something */ }
xxx = new MyObj();
xxx.selectfn(1,"ciao");
//call xxx.fn1("ciao");
请参阅控制台以获取回复。