创建对象的几种方式

6/24/2020 Javascript

# 1.对象字面量

let person = { name: 'Jioho', sex: 'man', age: 22 }
1

# 2. 用 function 来模拟无参的构造函数

function Person() {}
// 定义一个function,如果使用new"实例化"
// 该function可以看作是一个Class
var person = new Person()
person.name = 'Jioho'
person.age = '22'
person.work = function() {
  console.log(this.name + ' is codinig')
}
person.work() // jioho is coding
1
2
3
4
5
6
7
8
9
10

# 3. 用 function 来模拟参构造函数来实现

// 用this关键字定义构造的上下文属性
function Person(name, age, skill) {
  this.name = name //this作用域:当前对象
  this.age = age
  this.skill = skill
  this.word = function() {
    console.log(this.name + ' skill is ' + this.skill)
  }
}

//实例化、创建对
var author = new Person('Jioho', 25, 'coding')象
author.word() // Jioho skill is coding
1
2
3
4
5
6
7
8
9
10
11
12
13

# 4. 用工厂方式来创建(内置对象)

var dog = new Object()
dog.name = '旺财'
dog.age = 3
dog.shout = function() {
  console.log('我是' + this.name + ',汪汪汪......')
}
dog.shout()
1
2
3
4
5
6
7

# 5. 用原型方式来创建

function Dog() {}
Dog.prototype.name = '旺财'
Dog.prototype.shout = function() {
  console.log('我是' + this.name + ',汪汪汪......')
}
var wangcai = new Dog()
wangcai.shout()
1
2
3
4
5
6
7

# 6. 用混合方式来创建

function Car(name, price) {
  this.name = name
  this.price = price
}
Car.prototype.sell = function() {
  console.log('我是' + this.name + ',我现在卖' + this.price + '万元')
}
var camry = new Car('凯美瑞', 27)
camry.sell()
1
2
3
4
5
6
7
8
9
Last Updated: 5/9/2021, 10:45:03 PM