有无关键字new的区别

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

const lydia = new Person("Lydia", "Hallie");
const sarah = Person("Sarah", "Smith");

console.log(lydia);
console.log(sarah);
  • A: Person {firstName: "Lydia", lastName: "Hallie"} and undefined

  • B: Person {firstName: "Lydia", lastName: "Hallie"} and Person {firstName: "Sarah", lastName: "Smith"}

  • C: Person {firstName: "Lydia", lastName: "Hallie"} and {}

  • D: Person {firstName: "Lydia", lastName: "Hallie"} and ReferenceError

对于sarah,我们没有使用new关键字。 使用new时,它指的是我们创建的新空对象。 但是,如果你不添加new它指的是全局对象!

我们指定了this.firstName等于'Sarahthis.lastName等于Smith。 我们实际做的是定义global.firstName ='Sarah'global.lastName ='Smith。 sarah本身的返回值是undefined

 

答案: A

posted @ 2019-06-26 11:46  最爱小虾  阅读(162)  评论(0编辑  收藏  举报