首页 > 解决方案 > 在 Javascript 中,如何在对象内使用(全局)函数?该函数会做复杂的事情,并会在创建对象时使用

问题描述

所以,我正在考虑创建一个函数来做一些事情,然后在以后创建的不同对象中使用相同的函数。

下面的代码中有两个实例:测试 (01) 和注释掉 (02),反之亦然。

"use strict";

function fullName() {
    return this.firstName + " " + this.lastName;
}

const person = {
    firstName: "Anant",
    lastName: "Ghotale"
    completeName: fullName.call(person) // (01) does not work
};

//person.completeName = fullName.call(person); (02) this works


console.clear();
console.log(person.completeName);

(02) 有效,但 (01) 无效。

也就是说,在外部创建一个新属性,person同时使用 call to put this = person 可以,但不能在其中。

这些是我的问题:

  1. 如何在对象内使用(调用)函数?
  2. 在对象内部调用函数是一种愚蠢的做法吗?有没有更好的方法来完成同样的任务?

标签: javascriptfunctionobjectcall

解决方案


您可能想为此使用吸气剂

function fullName() {
  return this.firstName + " " + this.lastName;
}

const person = {
  firstName: "Anant",
  lastName: "Ghotale",
  get completeName() {
    return fullName.call(this)
  }
};

console.log(person.completeName)


推荐阅读