五、Objects

2018-07-24  本文已影响0人  HarryWX

对象概述

对象和属性

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

枚举一个对象的所有属性

创建新对象

使用对象初始化器

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

使用构造函数

  1. 通过创建一个构造函数来定义对象的类型。首字母大写是非常普遍而且很恰当的惯用法。
  2. 通过new创建对象实例。
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
var mycar = new Car("Eagle", "Talon TSi", 1993);

使用Object.create方法

// Animal properties and method encapsulation
var Animal = {
  type: "Invertebrates", // Default value of properties
  displayType : function() {  // Method which will display type of Animal
    console.log(this.type);
  }
}

// Create new animal type called animal1 
var animal1 = Object.create(Animal);
animal1.displayType(); // Output:Invertebrates

// Create new animal type called Fishes
var fish = Object.create(Animal);
fish.type = "Fishes";
fish.displayType(); // Output:Fishes

继承

上一篇下一篇

猜你喜欢

热点阅读