代码语言: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"}
andundefined
- B:
Person {firstName: "Lydia", lastName: "Hallie"}
andPerson {firstName: "Sarah", lastName: "Smith"}
- C:
Person {firstName: "Lydia", lastName: "Hallie"}
and{}
- D:
Person {firstName: "Lydia", lastName: "Hallie"}
andReferenceError
答案: A
对于sarah
,我们没有使用new
关键字。使用new
时,它指的是我们创建的新空对象。但是,如果你不添加new
它指的是全局对象!
我们指定了this.firstName
等于'Sarah
和this.lastName
等于Smith
。我们实际做的是定义global.firstName ='Sarah'
和global.lastName ='Smith
。 sarah
本身的返回值是undefined
。