我是 JavaScript 的初学者,我发现一个概念非常困惑。考虑以下代码:
var person = {
firstName :"Penelope",
lastName :"Barrymore",
// Since the "this" keyword is used inside the showFullName method below, and the showFullName method is defined on the person object,
// "this" will have the value of the person object because the person object will invoke showFullName ()
showFullName:function () {
console.log (this.firstName + " " + this.lastName);
}
}
person.showFullName (); // Penelope Barrymore
person 是类或函数还是只是一个变量?
如果假设那个人是一个类,代码 person.showFullName ();
是调用它的正确方法吗,因为在 C# 或我们编写的任何其他语言中
person perObj = new person();
perObj.showFullName();
?
最佳答案
person
是一个对象。它有 3 个属性,名为 firstName
, lastName
, 和 showFullName
.前两个属性包含字符串。最后一个属性包含一个函数。
当您使用语法 <expression>.<function>(<arguments>)
调用函数时, 其中<expression>
评估为一个对象和<function>
是其属性之一的名称,然后在函数运行时特殊变量 this
设置为对象。就是这样this.firstName
和 this.lastName
能够访问对象的这些属性。
当只有一个对象时,此功能不是很有用,因为它可以轻松地使用 person
多变的。但是您可以对多个对象使用相同的函数。
function showFull() {
console.log(this.firstName + " " + this.lastName);
}
var person1 = {
firstName: "Penelope",
lastName: "Barrymore",
showFullName: showFull
};
var person2 = {
firstName: "John",
lastName: "Smith",
showFullName: showFull
}
person1.showFullName(); // Penelope Barrymore
person2.showFullName(); // John Smith
关于javascript - 深入理解 JavaScript : is it a class, 一个函数,还是一个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34555701/