對象構(gòu)造器
本例使用函數(shù)來構(gòu)造對象:
function person(firstname, lastname, age, eyecolor) { this.firstname = firstname; this.lastname = lastname; this.age = age; this.eyecolor = eyecolor; }
在JavaScript中,this通常指向的是我們正在執(zhí)行的函數(shù)本身,或者是指向該函數(shù)所屬的對象(運行時)
function movie(title, director) {
this.title = ;
this.director =;
}
創(chuàng)建 JavaScript 對象實例
一旦您有了對象構(gòu)造器,就可以創(chuàng)建新的對象實例,就像這樣:
var myFather = new person("John","Doe",50,"blue"); var myMother = new person("Sally","Rally",48,"green"); document.write(myFather.age); // -> 50 document.write(myMother.name); // -> Sally
提示: myFather 和 myMother 是 person 對象的實例,它們的屬性分配給相應(yīng)的值。
創(chuàng)建對象
請考慮以下示例。
function person (name, age) { this.name = name; this.age = age; } var John = new person("John", 25); var Loen = new person("Loen", 28);
使用點語法訪問對象的屬性。