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

new 关键字有什么作用? #293

Open
Sogrey opened this issue Sep 16, 2020 · 0 comments
Open

new 关键字有什么作用? #293

Sogrey opened this issue Sep 16, 2020 · 0 comments

Comments

@Sogrey
Copy link
Owner

Sogrey commented Sep 16, 2020

new关键字与构造函数一起使用以创建对象:

function Employee(name, position, yearHired) {
  this.name = name;
  this.position = position;
  this.yearHired = yearHired;
};

const emp = new Employee("Marko Polo", "Software Developer", 2017);

new关键字做了4件事:

  • 创建空对象 {}
  • 将空对象分配给 this
  • 将空对象的**proto**指向构造函数的prototype
  • 如果没有使用显式return语句,则返回this

看下面事例:

function Person() { this.name = '前端小智' }

根据上面描述的,new Person()做了:

  • 创建一个空对象:var obj = {}
  • 将空对象分配给 this 值:this = obj
  • 将空对象的**proto__指向构造函数的prototype:this.__proto** = Person().prototype
  • 返回this:return this

new操作符具体干了什么呢? #36

@Sogrey Sogrey added this to javascript in Web面经题 Sep 16, 2020
@Sogrey Sogrey mentioned this issue Dec 2, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Web面经题
javascript
Development

No branches or pull requests

1 participant