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的构造函数 #10

Open
lfb opened this issue Jul 20, 2019 · 0 comments
Open

理解JavaScript的构造函数 #10

lfb opened this issue Jul 20, 2019 · 0 comments
Assignees
Labels

Comments

@lfb
Copy link
Owner

lfb commented Jul 20, 2019

构造函数

JS构造函数也是普通函数,区别就是使用new操作符调用函数,就可以称为构造函数。通过new操作符调用函数可以创建一个新的对象。比如:

function Person(name) {
    this.name = name;
}

let p = new Person('bobobo');
console.log(typeof p); // 'object'
console.log(p.name); // 'bobobo'

new操作符

之前学习this的指向就知道了使用new调用函数,那么this指向的是创建出来的新对象。那么new操作符调用的过程经历的步骤:

  • 创建一个新的对象
  • 链接原型链
  • 把this指向这个新对象
  • 返回这个新对象

模拟实现new操作符

// 实现
function create(Con, ...args) {
  let obj = {}
  // setPrototypeOf设置一个对象的 prototype 对象
  Object.setPrototypeOf(obj, Con.prototype)
  let result = Con.apply(obj, args)
  
  return result instanceof Object ? result : obj
}

// 用法
function Person(name) {
  this.name = name
}
const p = create(Person, 'bobo');

/** 
 * 实现来源于作者:yck
 * 链接:https://juejin.im/post/5c7b963ae51d453eb173896e
 */
@lfb lfb self-assigned this Jul 20, 2019
@lfb lfb added the 原型 label Jul 20, 2019
This was referenced Jul 20, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant