JavaScript 对象

JavaScript 大约 1014 字

创建对象

方式一

var person = {
    firstName:"Bill",
    lastName:"Gates",
    age:62,
    eyeColor:"blue"
};

方式二

function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

var person = new Person("Bill", "Gates", 62, "blue");

方式三

var person = new Object();
person.firstName = "Bill";
person.lastName = "Gates";
person.age = 50;
person.eyeColor = "blue"; 

访问属性

objectName.property           // person.age

objectName["property"]       // person["age"]

objectName[expression]       // x = "age"; person[x]

删除属性

delete person.age;   // 或 delete person["age"];

Getter

var person = {
  language : "en",
  get lang() {
    return this.language;
  }
};

Setter

var person = {
  language : "",
  set lang(lang) {
    this.language = lang;
  }
};

Object.defineProperty()

Object.defineProperty(person, "add", {
    set : function (value) {this.counter += value;}
});

Object.prototype

Person为创建对象方式二中的对象。

Person.prototype.nationality = "English";
阅读 192 · 发布于 2021-06-04

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批