此:对多个对象执行相同的代码

问题描述 投票:-1回答:4
function importantPerson () {
    console.log (this.name)
}


const name = 'Sunny';
const obj1 = {
    name : 'Cassy',
    importantPerson : importantPerson
}

有人可以解释这段代码的含义吗?importantPerson : importantPerson

javascript this
4个回答
0
投票

认为该属性是实际功能的地址持有者。

importantPerson (property holding pointer to function) : importantPerson(function)

所以当您这样做

obj1.importanPerson()

调用importantPersonobj1键将执行该功能。


0
投票

有一个对象obj1,其键为[“ importantPerson”],其值为函数importantPerson

function importantPerson () {
    console.log (this.name)
}


const name = 'Sunny';
const obj1 = {
    name : 'Cassy',
    importantPerson : importantPerson
}


obj1.importantPerson()

0
投票

[@Nick评论:

importantPerson是对象中的一个属性,它指向您的personalPerson函数的参考]

尝试以下示例以使其更清晰:

function importantPerson() {
    return this.name;
}

const name = 'Sunny';
const obj1 = {
    name: 'Cassy',
    importantPerson: importantPerson
}
const obj2 = {
    name: 'name2',
    importantPerson: importantPerson
}
console.log(obj1.importantPerson());
console.log(obj2.importantPerson());

0
投票
obj1内的

importantPerson是一个引用ImportantPerson函数的键。所以当你做这个:

obj1.importantPerson

您正在调用一个重要的人函数

© www.soinside.com 2019 - 2024. All rights reserved.