以下是node.js的代码,this指代的问题。很纳闷,在write函数里,this.tableName居然是未定义。其实一开始也觉得未定义正确。还有回调函数中的this,通通会改变成当前的对象。但是js却表现的不一样了,为什么?求解
var DailyworkModule=require(DATACLASS+"mongodb.js");
var DailyWork = new DailyworkModule();
module.exports=function(){
this.tableName="today";
this.init=function(response,request){
res=response;
req=request;
};
var self=this;
this.write=function(){
//console.log(this.tableName); 为什么读取不到this.tableName,返回的是undefined
console.log(self.tableName);
DailyWork.insert(self.tableName,{'name':'fuhui2','tel':'183×××'},function(ret){
console.log(ret);
});
console.log("执行完成");
};
this.view=function(){
DailyWork.select({'and':[],'or':[]},"","","",function(result){
res.render('dailywite.jade',{'result':result});
});
};
} 太坑了,都是js,是我哪里理解出错了吗,还是意识就是错的?
function child() {
this.name = 'kobe';
this.calback = function (cb) { //回调函数当作了一个对象处理
alert(this.name); //返回的是kobe
cb();
}
}
function Lakers() {
this.name = 'kobe bryant';
this.age = '28';
this.gender = 'boy';
this.child = function () {
return new child;
}
this.change = function () {
var child_ = this.child();
child_.calback(function () {
this.name = 'bryant';
alert(this.name); //返回的是bryant,说明this指代了回调函数本身,并不是child_
});
alert(this.name); //返回kobe bryant,说明this指代的是Lakers对象
}
}
var people = new Lakers();
people.change();
/**
有时候,我在一个程序代码中,多次需要使用某对象的属性或方法,照以前的写法,都是通过:对象.属性或者对象.方法这样的方式来分别获得该对象的属性和方法,着实有点麻烦,学习了with语句后,可以通过类似如下的方式来实现:
*/
with (people)
{
var str = '姓名: ' + name + '<br>';
str += '年龄:' + age + '<br>';
str += '性别:' + gender + '<br>';
str += '修改:' + change;
document.write(str);
} 原文:http://blog.csdn.net/whynottrythis/article/details/44878097