javascript深入瞭解,深入淺出javascript
以下是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,返回的是undefinedconsole.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的簡單代碼,這是胡寫的,只是驗證問題: 建立newLakes對象,調用它的change方法。然後change調用this.child調用成功了,說明change裡的this是Lakers對象,然後返回child對象,調用它的callback方法,它有一個回呼函數作為參數。在回呼函數裡alert會返回undefined ,這裡很正常,因為回呼函數cb它是獨立出來的,this訪問不到很應該,最後change再alert返回 kobe bryant。
太坑了,都是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);}
還有比較不能理解的是,在MySQL的資料操作中this.tableName居然可以,是因為類的問題嗎?下面這段代碼,this.tableName是可以訪問的
this.findOneByID=function(whereJson,callback){db.query('select * from '+this.tableName+' where ?',whereJson,function(err,result){if(err){console.log('GetData Error:'+err.message);db.end();callback(false);}else{if(result){//如果查到資料則返回一條資料,否則返回空資料callback(result.shift());}else{callback(result)}}}); }
總覺得js不應該這樣的,突然有意外發現:我代碼的路由雖然沒有使用到 eval,但基本原理是這樣的,對於路徑中的參數,去建構函式跟方法,使用了call這個函數。
調用該函數,發現第一個返回的是‘dog’,第二個是undefined。應該是這裡出的問題。
var dog = function () { this.table = 'dog'; this.say = function () { alert(this.table); }}var cls = 'dog';var obj = eval('new ' + cls + '()');obj.say();obj['say'].call();
靠,還真是這裡的問題
類似下面這樣修改路由,ok了。
obj['say'].call(obj);
人氣慘淡啊......