javascript - 在 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 可以,但不能在其中。
这些是我的问题:
- 如何在对象内使用(调用)函数?
- 在对象内部调用函数是一种愚蠢的做法吗?有没有更好的方法来完成同样的任务?
解决方案
您可能想为此使用吸气剂。
function fullName() {
return this.firstName + " " + this.lastName;
}
const person = {
firstName: "Anant",
lastName: "Ghotale",
get completeName() {
return fullName.call(this)
}
};
console.log(person.completeName)
推荐阅读
- c# - 如何在 Windows 窗体上更快地绘制圆圈?
- c# - 生成的 Excel 文件在不同系统中显示不同的日期值(Asp.net Web 应用程序)
- django - 当我使用动态 url 时,django 创建了问题页面未找到
- go - 无法从 go 频道获取消息
- c# - SwashBuckle/Swagger 隐藏了我的不可变属性
- reactjs - 如何在反应原生应用程序中替换 componentWillReceiveProps?
- javascript - 动态生成 HTML 表格 - 从 Jinja/Flask/Python 访问二维对象列表
- c - Yacc,联合中的结构指针
- python - 偏好值的变化不影响亲和传播聚类的结果
- spring-boot - Sprint Data JPA - save() 方法在表中插入重复项