2012-06-19 60 views
1

只是想知道,有以下簡單的代碼:的JavaScript OOP方法

var object1 = { 
    name: function(){ 
     return 'myName'; 
    }, 
    surname: function(){ 
     return 'mySurname'; 
    } 
}; 

爲什麼JS返回在這種情況下object1.name function()

爲什麼JS返回預期結果myName如果我調用object1.name()?

回答

2
  1. 引用name回報什麼name在這種情況下 –,一個功能。
  2. 調用name通過附加(),即name(),返回一個值–字符串"myName"

My answerWhen do I use parenthesis and when do I not?提供更多的細節。

+0

謝謝,你的回答有完整。 –

1
object1.name;//Returns the function declaration 
object1.name();//Calls the function and returns its value 

它的工作原理類似下面的代碼:

var myFn = function(){ 
    return "This is the return value of this function"; 
} 
alert(myFn);//Alerts the myFn function's declaration 
alert(myFn());//Alerts "This is the return value of this function" 
1

因爲object1.name您所呼叫的函數聲明

object1.name()你調用的函數