Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

JavaScript 設計成簡單的物件樣式。一個物件是一些屬性的集合,而屬性是鍵與值之間的關聯。一個屬性能夠是一個函數 (Function),也叫做方法 (Method)。此外,物件是瀏覽器預定義的,你也可以定義你自己的物件。

這一章會介紹怎樣去使用物件,屬性,函數及方法,以及怎樣去建立你自己的物件。

物件概覽

物件在 JavaScript 中,和很多其它的編程語言一樣,能夠比喻成現實生活中的物件,物件的概念能夠理解為現實生活中真實的物件。

在 JavaScript 中,物件是有屬性及類型的,獨立的實體,例如將物件比喻為柸,柸有顏色、設計、重量、原料等等。同樣地,JavaScript 物件能夠有屬性,用來定義他的特性。

物件及屬性

一個  JavaScript 物件會有它相關的屬性,而一個物件的屬性可以解釋成是一個變數依附在某個物件之下。 物件屬性基本上跟一般的 JavaScript 變數並無不同,除了它們是「依附」在某個物件之下,一個物件的屬性定義了一個物件的特性。 你可以定義一個物件屬性用一個「.」將它們連接:

objectName.propertyName

就像大多數的 JavaScript 變數,你可以定義一個物件的名字 ( 就像任一個普通的變數 )  和他的屬性名使用大小寫區分的方式,你也可以在定義屬性的時候指定值給它。舉例來說,我們在下方製作了一個名為 myCar 的物件,並且給了他三個屬性名叫: make, model, 還有 year as follows:

var myCar = new Object();
myCar.make = "Ford";
myCar.model = "Mustang";
myCar.year = 1969;

JavaScript 物件的屬性 can also be accessed or set using a bracket notation. Objects are sometimes called associative arrays, since each 屬性 is associated with a string value that can be used to access it. So, for example, you could access the properties of the myCar object as follows:

myCar["make"] = "Ford";
myCar["model"] = "Mustang";
myCar["year"] = 1969;

物件的屬性名字可以使用任何有效的 JavaScript 字串、或是任何可以轉變成字串的東西,包含空字串。However, any property name that is not a valid JavaScript identifier (for example, a property name that has space or dash, or starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime). Examples are as follows:

var myObj = new Object(),
    str = "myString",
    rand = Math.random(),
    obj = new Object();

myObj.type              = "Dot syntax";
myObj["date created"]   = "String with space";
myObj[str]              = "String value";
myObj[rand]             = "Random Number";
myObj[obj]              = "Object";
myObj[""]               = "Even an empty string";

console.log(myObj);

You can also access properties by using a string value that is stored in a variable:

var propertyName = "make";
myCar[propertyName] = "Ford";

propertyName = "model";
myCar[propertyName] = "Mustang";

You can use the bracket notation with for...in to iterate over all the enumerable properties of an object. To illustrate how this works, the following function displays the properties of the object when you pass the object and the object's name as arguments to the function:

function showProps(obj, objName) {
  var result = "";
  for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
        result += objName + "." + i + " = " + obj[i] + "\n";
    }
  }
  return result;
}

So, the function call showProps(myCar, "myCar") would return the following:

myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969

所有事物都是物件

在JavaScript中,差不多所有事物都是物件,除了 null 及 undefined 以外其它所有原始類型都可以看成是物件,它們都可以付予屬性(有些類型被付予的屬性不能永久保存),以及擁有物件的特性。

列舉一個物件中的所有屬件

Starting with ECMAScript 5, there are three native ways to list/traverse object properties:

  • for...in loops
    This method traverses all enumerable properties of an object and its prototype chain
  • Object.keys(o)
    This method returns an array with all the own (not in the prototype chain) enumerable properties names ("keys") of an object o.
  • Object.getOwnPropertyNames(o)
    This method returns an array containing all own properties names (enumerable or not) of an object o.

In ECMAScript 5, there is no native way to list all properties of an object. However, this can be achieved with the following function:

function listAllProperties(o){     
	var objectToInspect;     
	var result = [];
	
	for(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)){  
		result = result.concat(Object.getOwnPropertyNames(objectToInspect));  
	}
	
	return result; 
}

This can be useful to reveal "hidden" properties (properties in the prototype chain which are not accessible through the object, because another property has the same name earlier in the prototype chain). Listing accessible properties only can easily be done by removing duplicates in the array.

建立新的物件

JavaScript has a number of predefined objects. In addition, you can create your own objects. In JavaScript 1.2 and later, you can create an object using an object initializer. Alternatively, you can first create a constructor function and then instantiate an object using that function and the new operator.

使用物件的初始化

In addition to creating objects using a constructor function, you can create objects using an object initializer. Using object initializers is sometimes referred to as creating objects with literal notation. "Object initializer" is consistent with the terminology used by C++.

The syntax for an object using an object initializer is:

var obj = { property_1:   value_1,   // property_# may be an identifier...
            2:            value_2,   // or a number...
            // ...,
            "property n": value_n }; // or a string

where obj is the name of the new object, each property_i is an identifier (either a name, a number, or a string literal), and each value_i is an expression whose value is assigned to the property_i. The obj and assignment is optional; if you do not need to refer to this object elsewhere, you do not need to assign it to a variable. (Note that you may need to wrap the object literal in parentheses if the object appears where a statement is expected, so as not to have the literal be confused with a block statement.)

If an object is created with an object initializer in a top-level script, JavaScript interprets the object each time it evaluates an expression containing the object literal. In addition, an initializer used in a function is created each time the function is called.

The following statement creates an object and assigns it to the variable x if and only if the expression cond is true.

if (cond) var x = {hi: "there"};

The following example creates myHonda with three properties. Note that the engine property is also an object with its own properties.

var myHonda = {color: "red", wheels: 4, engine: {cylinders: 4, size: 2.2}};

You can also use object initializers to create arrays. See array literals.

In JavaScript 1.1 and earlier, you cannot use object initializers. You can create objects only using their constructor functions or using a function supplied by some other object for that purpose. See Using a constructor function.

使用建構函數 (Constructor)

Alternatively, you can create an object with these two steps:

  1. Define the object type by writing a constructor function. There is a strong convention, with good reason, to use a capital initial letter.
  2. Create an instance of the object with new.

To define an object type, create a function for the object type that specifies its name, properties, and methods. For example, suppose you want to create an object type for cars. You want this type of object to be called car, and you want it to have properties for make, model, and year. To do this, you would write the following function:

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

Notice the use of this to assign values to the object's properties based on the values passed to the function.

Now you can create an object called mycar as follows:

var mycar = new Car("Eagle", "Talon TSi", 1993);

This statement creates mycar and assigns it the specified values for its properties. Then the value of mycar.make is the string "Eagle", mycar.year is the integer 1993, and so on.

You can create any number of car objects by calls to new. For example,

var kenscar = new Car("Nissan", "300ZX", 1992);
var vpgscar = new Car("Mazda", "Miata", 1990);

An object can have a property that is itself another object. For example, suppose you define an object called person as follows:

function Person(name, age, sex) {
  this.name = name;
  this.age = age;
  this.sex = sex;
}

and then instantiate two new person objects as follows:

var rand = new Person("Rand McKinnon", 33, "M");
var ken = new Person("Ken Jones", 39, "M");

Then, you can rewrite the definition of car to include an owner property that takes a person object, as follows:

function Car(make, model, year, owner) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.owner = owner;
}

To instantiate the new objects, you then use the following:

var car1 = new Car("Eagle", "Talon TSi", 1993, rand);
var car2 = new Car("Nissan", "300ZX", 1992, ken);

Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the arguments for the owners. Then if you want to find out the name of the owner of car2, you can access the following property:

car2.owner.name

Note that you can always add a property to a previously defined object. For example, the statement

car1.color = "black";

adds a property color to car1, and assigns it a value of "black." However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the car object type.

使用 Object.create 方法

Objects can also be created using the Object.create method. This method can be very useful, because it allows you to choose the prototype object for the object you want to create, without having to define a constructor function. For more detailed information on the method and how to use it, see Object.create method

繼承

All objects in JavaScript inherit from at least one other object. The object being inherited from is known as the prototype, and the inherited properties can be found in the prototype object of the constructor.

給物件屬件編索引

In JavaScript 1.0, you can refer to a property of an object either by its property name or by its ordinal index. In JavaScript 1.1 and later, however, if you initially define a property by its name, you must always refer to it by its name, and if you initially define a property by an index, you must always refer to it by its index.

This restriction applies when you create an object and its properties with a constructor function (as we did previously with the Car object type) and when you define individual properties explicitly (for example, myCar.color = "red"). If you initially define an object property with an index, such as myCar[5] = "25 mpg", you can subsequently refer to the property only as myCar[5].

The exception to this rule is objects reflected from HTML, such as the forms array. You can always refer to objects in these arrays by either their ordinal number (based on where they appear in the document) or their name (if defined). For example, if the second <FORM> tag in a document has a NAME attribute of "myForm", you can refer to the form as document.forms[1] or document.forms["myForm"] or document.myForm.

定義一個物件類型的屬性

You can add a property to a previously defined object type by using the prototype property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. The following code adds a color property to all objects of type car, and then assigns a value to the color property of the object car1.

Car.prototype.color = null;
car1.color = "black";

See the prototype property of the Function object in the JavaScript Reference for more information.

定義方法 (Method)

method 是個屬於object property的function, Methods 跟定義一般function一樣,但他們必須是屬於object的property,舉例:

objectName.methodname = function_name;

var myObj = {
  myMethod: function(params) {
    // ...do something
  }
};

where objectName is an existing object, methodname is the name you are assigning to the method, and function_name is the name of the function.

You can then call the method in the context of the object as follows:

object.methodname(params);

You can define methods for an object type by including a method definition in the object constructor function. For example, you could define a function that would format and display the properties of the previously-defined car objects; for example,

function displayCar() {
  var result = "A Beautiful " + this.year + " " + this.make
    + " " + this.model;
  pretty_print(result);
}

where pretty_print is a function to display a horizontal rule and a string. Notice the use of this to refer to the object to which the method belongs.

You can make this function a method of car by adding the statement

this.displayCar = displayCar;

to the object definition. So, the full definition of car would now look like

function Car(make, model, year, owner) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.owner = owner;
  this.displayCar = displayCar;
}

Then you can call the displayCar method for each of the objects as follows:

car1.displayCar();
car2.displayCar();

This produces the output shown in the following figure.

Image:obja.gif

Figure 7.1: Displaying method output.

使用 this 作為物件參考

JavaScript has a special keyword, this, that you can use within a method to refer to the current object. For example, suppose you have a function called validate that validates an object's value property, given the object and the high and low values:

function validate(obj, lowval, hival) {
  if ((obj.value < lowval) || (obj.value > hival))
    alert("Invalid Value!");
}

Then, you could call validate in each form element's onchange event handler, using this to pass it the element, as in the following example:

<input type="text" name="age" size="3"
  onChange="validate(this, 18, 99)">

In general, this refers to the calling object in a method.

When combined with the form property, this can refer to the current object's parent form. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onclick event handler uses this.form to refer to the parent form, myForm.

<form name="myForm">
<p><label>Form name:<input type="text" name="text1" value="Beluga"></label>
<p><input name="button1" type="button" value="Show Form Name"
     onclick="this.form.text1.value = this.form.name">
</p>
</form>

定義 Getters 及 Setters

 getter 是個用來“取得”特定屬性的值的方法. setter 是用來”設定“特定屬性的值”的”方法. 你可以在任何可增加新屬性的predefined core object 或 user-defined object 定義 getters 與 setters. 我們用object literal syntax來作為定義 getters and setters 的syntax .

JavaScript 1.8.1 note

Starting in JavaScript 1.8.1, setters are no longer called when setting properties in object and array initializers.

The following JS shell session illustrates how getters and setters could work for a user-defined object o. The JS shell is an application that allows developers to test JavaScript code in batch mode or interactively. In Firefox you can get a JS shell by pressing Ctrl+Shift+K.

js> var o = {a: 7, get b() {return this.a + 1;}, set c(x) {this.a = x / 2}};
[object Object]
js> o.a;
7
js> o.b;
8
js> o.c = 50;
js> o.a;
25

The o object's properties are:

  • o.a — a number
  • o.b — a getter that returns o.a plus 1
  • o.c — a setter that sets the value of o.a to half of the value o.c is being set to

Please note that function names of getters and setters defined in an object literal using "[gs]et property()" (as opposed to __define[GS]etter__ ) are not the names of the getters themselves, even though the [gs]et propertyName(){ } syntax may mislead you to think otherwise. To name a function in a getter or setter using the "[gs]et property()" syntax, define an explicitly named function programmatically using Object.defineProperty (or the Object.prototype.__defineGetter__ legacy fallback).

This JavaScript shell session illustrates how getters and setters can extend the Date prototype to add a year property to all instances of the predefined Date class. It uses the Date class's existing getFullYear and setFullYear methods to support the year property's getter and setter.

These statements define a getter and setter for the year property:

js> var d = Date.prototype;
js> Object.defineProperty(d, "year", {
    get: function() {return this.getFullYear() },
    set: function(y) { this.setFullYear(y) }
});

These statements use the getter and setter in a Date object:

js> var now = new Date;
js> print(now.year);
2000
js> now.year = 2001;
987617605170
js> print(now);
Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001

過時的語法

In the past, JavaScript supported several other syntaxes for defining getters and setters. None of these syntaxes were supported by other engines, and support has been removed in recent versions of JavaScript. See this dissection of the removed syntaxes for further details on what was removed and how to adapt to those removals.

摘要

In principle, getters and setters can be either

  • defined using object initializers, or
  • added later to any object at any time using a getter or setter adding method.

When defining getters and setters using object initializers all you need to do is to prefix a getter method with get and a setter method with set. Of course, the getter method must not expect a parameter, while the setter method expects exactly one parameter (the new value to set). For instance:

var o = {
  a: 7,
  get b() { return this.a + 1; },
  set c(x) { this.a = x / 2; }
};

Getters and setters can also be added to an object at any time after creation using the Object.defineProperties method. This method's first parameter is the object on which you want to define the getter or setter. The second parameter is an object whose property names are the getter or setter names, and whose property values are objects for defining the getter or setter functions. Here's an example that defines the same getter and getter used in the previous example:
 

var o = { a:0 }

Object.defineProperties(o, {
    "b": { get: function () { return this.a + 1; } },
    "c": { set: function (x) { this.a = x / 2; } }
});

o.c = 10 // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
console.log(o.b) // Runs the getter, which yields a + 1 or 6

Which of the two forms to choose depends on your programming style and task at hand. If you already go for the object initializer when defining a prototype you will probably most of the time choose the first form. This form is more compact and natural. However, if you need to add getters and setters later — because you did not write the prototype or particular object — then the second form is the only possible form. The second form probably best represents the dynamic nature of JavaScript — but it can make the code hard to read and understand.

Prior to Firefox 3.0, getter and setter are not supported for DOM Elements. Older versions of Firefox silently fail. If exceptions are needed for those, changing the prototype of HTMLElement (HTMLElement.prototype.__define[SG]etter__) and throwing an exception is a workaround.

With Firefox 3.0, defining getter or setter on an already-defined property will throw an exception. The property must be deleted beforehand, which is not the case for older versions of Firefox.

參見

刪除屬性

You can remove a non-inherited property by using the delete operator. The following code shows how to remove a property.

//Creates a new object, myobj, with two properties, a and b.
var myobj = new Object;
myobj.a = 5;
myobj.b = 12;

//Removes the a property, leaving myobj with only the b property.
delete myobj.a;
console.log ("a" in myobj) // yields "false"

You can also use delete to delete a global variable if the var keyword was not used to declare the variable:

g = 17;
delete g;

See delete for more information.

參見

文件標籤與貢獻者

 此頁面的貢獻者: pytseng, jackblackevo, iigmir, jigs12, YuXiangYen, teoli, steely.wing
 最近更新: pytseng,