2014年5月30日 星期五

[js] JavaScript的"類別"用法 ~解析~

上篇主要說明了js function模擬類別的用法

細節有幾個部分可以說說

1. 宣告了function可以直接呼叫,也可以加上new當作建構式來用
    差別是this與prototype設定 (prototype介紹繼承再介紹吧)

2. 如果裡面沒有回傳值,在當作建構式使用時,會回傳this物件
    如果裡面回傳的是Primitive Data Type時,預設也會回傳this物件
    如果裡面有回傳物件,就是直接回傳新的物件

3.  當我們宣告var fn = function(){};的時候其實也是在宣告一個attribute fn
     只是它是個function object

4. 當在function中存取一個attribute
    而且如果沒有在function裡面宣告的話
    會往"外面"尋找相同名字的attribute

5. private attribute與method是利用第3,4來完成的
建立不能直接存取到的method與attribute
(硬是要應該還是可以啦 = =)

6. 第4點說的"外面"指的是外面的scope (JavaScript是以function來區分scope)
     所以會往這個function的外面的function來尋找
     而不會找本身所在的物件所擁有的function(不會從this先找起)

ex.
// 以下範例使用getCoord()
// 預設找外面的function的getCoord而不是本身物件的getCoord
var Person = function(_name, _age){
var x = 10,  
y = 15;  
var getCoord = function(){  
return "("+x+","+y+")";
};

this.name = _name,
this.age = _age,
this.moveX = function(step){
x += step;
};
this.moveY = function(step){
y += step;
};
this.getCoord = function(){
return "["+x+","+y+"]";
};
this.hi = function(){
return this.name+"在"+getCoord()+":hi!";
};
};
var p = new Person("丹丹", 18);
p.hi(); // 丹丹在(10, 15): hi!

Q. 範例的hi() 如果把this.name 改成name會如何?

A. 因為在hi()裡面找不到name所以會到Person()裡面找
但是Person()也找不到就會找global的name
應該會出現name is not defined的錯誤訊息
       but 在chrome中測試,window裡面有個神奇的name屬性
       所以.... 其實也不會出錯啦~~

       ps. 用node js測試就出現錯誤訊息啦!!!

ReferenceError: name is not defined
    at hi (repl:20:8)
    at repl:1:3
    at REPLServer.self.eval (repl.js:110:21)
    at repl.js:249:20
    at REPLServer.self.eval (repl.js:122:7)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)

沒有留言:

張貼留言