Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Javascript之创建对象的方式及new 运算符的执行 #2

Open
feiyayshx opened this issue Jan 2, 2020 · 0 comments
Open

Javascript之创建对象的方式及new 运算符的执行 #2

feiyayshx opened this issue Jan 2, 2020 · 0 comments

Comments

@feiyayshx
Copy link
Owner

一. 创建对象的几种方式

1. 字面量创建对象

let person = new Object({
    name: '小花',
    age: 20
})
  • 简写形式(等价于new Object)
let person = {
    name: '小花',
    age: 20
}

2. 构造函数创建对象

function Person() {
    this.name = ’小花‘
    this.age = 20
}

let person = new Person()

3. Object.create() 创建对象

let person = Object.create({
    name: ’小花‘,
    age: 20
})

二. new 运算符背后的执行过程

1. 创建一个新对象,并继承该构造函数的原型对象;

2. 上下文ths指向新对象,同时执行构造函数中的代码;

注意:如果参数为空,则 new F() 等价于 new F

3. 若构造函数没有返回对象,new 出来的结果即为步骤1 创建的新对象;若构造函数返回一个对象,这个对象取代new 出来的结果。

  • 代码实现new 运算符

    var newFn = function(fn, ...args) {
          // 创建一个空对象,并继承构造函数的原型对象
          let obj = Object.create(fn.prototype)
          // this指向新创建的空对象,并执行构造函数中的代码
          let temp = fn.apply(obj, args)
          // 返回新创建的对象
          if (typeof temp === 'function') {
            return temp
          } else {
            return obj
          }
        }
    

    验证

    function Person(name, age) {
      this.name = name || '小花'
      this.age = age || 20
    }
    
    
      Person.prototype.speak = function() {
          console.log('Hi:' + this.name)
      }
    
      let p = newFn(Person,'xiaohua',20)
      console.log(p.name) // xiaohua
      p.speak() // Hi:xiahua
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant