我们是否将函数声明为变量的方法?

Are we declaring a function as a method on a variable?

我一直在自学 JS,并完成了 8 小时的基础课程。现在我正在学习另一门课程,在我看来,讲师正在使用点符号创建一个函数。我不确定这是不是正在发生的事情,我很难理解它到底在做什么。

function Person(fName, lName) {
    this.firstName = fName
    this.lastName = lName
}
const person1 =  new Person("Bruce", "Wayne")
const person2 =  new Person("Bat", "Man")

person1.getFullName = function () {
    return this.firstName + ' ' + this.lastName
}

console.log(person1.getFullName())

我感到困惑的部分是:

person1.getFullName = function () {
    return this.firstName + ' ' + this.lastName

}

我在 Person() 函数中看到我们正在创建一个名为 person1 的对象,使用“this”和一个键来传递参数作为这些键的值。然而,在我看来,有一个函数被分配给了 person1 对象,我假设是函数的名称,看起来像是 person1 对象上使用点表示法的方法。谁能解释一下这是如何工作的?

对象具有属性。

属性有值。

函数是一个值。

如果 属性 的值是一个函数,那么我们称之为方法。

仅此而已。

person1.getFullName = ...

是一个普通的赋值语句。它将右侧的值分配给 person1 中对象的 属性 getFullName。如果 属性 不存在,它将被创建。

函数和 JavaScript 中的任何其他函数一样是值(对象),因此它们可以在任何需要值的地方使用。

所以是的,person1.getFullName 将包含一个函数,它可以像任何其他函数一样被调用:person1.getFullName().

function Person(fName, lName) {
    this.firstName = fName
    this.lastName = lName
}
const person1 =  new Person("Bruce", "Wayne")
const person2 =  new Person("Bat", "Man")
 
person1.getFullName = function () {
    return this.firstName + ' ' + this.lastName
}

console.log(person1.getFullName())

基本上是为对象 person1 创建了一个名为 getFullName 的新 属性。这个新的 属性 被定义为 return person1 对象的名字和姓氏。因此,当您调用 console.log(person1.getFullName()) 时,这将打印 person1 的名字和姓氏。