选择篇(022)-下面代码的输出是什么?

2022-05-12 21:32:37 浏览数 (2)

代码语言:javascript复制
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
答案: A

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

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

0 人点赞