2015-05-02 91 views
0

我不明白第1行;這條線做什麼?myVar = {}是做什麼的?

phonebookEntry = {}; 

phonebookEntry.name = 'Oxnard Montalvo'; 
phonebookEntry.number = '(555) 555-5555'; 
phonebookEntry.phone = function() { 
    console.log('Calling ' + this.name + ' at ' + this.number + '...'); 
}; 

phonebookEntry.phone(); 
+1

它指定'phonebookEntry'是一個對象,以便爲它添加屬性。 [MDN |使用對象](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) –

+2

在JavaScript表達式中,「{}」只是創建一個新的空對象。 – Pointy

回答

2

這個phonebookEntry = {};是一個空的對象,沒有任何屬性。

其實,這相當於該phonebookEntry = new Object();

您可以驗證這是簡單的,如下:

typeof(phonebookEntry) 

將輸出"object"

JavaScript我們必須創造一個像上面,後來空物體附着有意義給我們,像下面的任何財產的能力:

phonebookEntry.name = 'Oxnard Montalvo'; 

或等價

phonebookEntry["name"] = 'Oxnard Montalvo'; 

此外,後者被稱爲括號記號

因爲它在MDN,在那裏你會找到關於此主題的全面和詳細的方法指出:

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name and a value. A property's value can be a function, in which case the property is known as a method. In addition to objects that are predefined in the browser, you can define your own objects. This chapter describes how to use objects, properties, functions, and methods, and how to create your own objects.

在上面的代碼中,我們定義的屬性name,與主要name和值'奧克斯納德蒙塔爾沃'。

4

該行創建了一個新的空對象,沒有屬性

phonebookEntry = {}; 

沒有它,你不能做到這一點:

phonebookEntry.name = 'Oxnard Montalvo'; 
phonebookEntry.number = '(555) 555-5555'; 

在JavaScript中還有另一種方式來聲明等同對象:

phonebookEntry = { 
    name : 'Oxnard Montalvo', 
    number : '(555) 555-5555', 
    phone : function() { 
     console.log('Calling ' + this.name + ' at ' + this.number + '...'); 
    } 
}; 

phonebookEntry.phone(); 

參考:MDN | Working With Objects

+0

嘿,我試過......但codecademy說SyntaxError:意外的令牌http://www.codecademy.com/courses/javascript-beginner-en-9Sgpi/2/1?curriculum_id=506324b3a7dffd00020bf661 –

+1

@ jubilukbabawakis它說「好「對我來說 – NaN

+0

@NaN是什麼? ..... –

0

這將是標準的方法,並會清除更多的概念。

function PhonebookEntry(name, number){ 
var privateName = name; 
var privateNumber = number; 
this.phone = function() { 
    console.log('Calling ' + privateName + ' at ' + privateNumber + '...'); 
}; 
}; 
phonebookEntry = new PhonebookEntry('Oxnard Montalvo', '(555) 555-5555'); 
phonebookEntry.phone(); 
phonebookEntry1 = new PhonebookEntry('Montalvo', '(222) 222-2222'); 
phonebookEntry1.phone(); 
+0

'This.name'和'this 。number'不存在於你構造的對象上(因爲'var'與'this'不一樣) –

+0

是的,忘了刪除它實際上,thnx – vinayakj

+0

隨着你的新編輯,你現在不需要'var'行因爲你只能訪問用作函數參數的標識符:) –