在Javascript,如何在对象内部使用(全局)函数?该函数会做复杂的事情,并在创建对象时使用
In Javascript, How to use a (global) function inside an object? The function would do complex stuff and would be used when creating objects
所以,我想创建一个函数来做一些事情,然后在稍后创建的不同对象中使用相同的函数。
下面的代码中有两个实例:测试(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
外面创建一个新的属性,同时使用调用把这个=人工作,但不在里面。
这些是我的问题:
- 如何在对象内部使用(调用)函数?
- 在对象内部调用函数,这是一种愚蠢的尝试吗?有没有更好的方法来完成同样的任务?
您可能想为此使用 getter。
function fullName() {
return this.firstName + " " + this.lastName;
}
const person = {
firstName: "Anant",
lastName: "Ghotale",
get completeName() {
return fullName.call(this)
}
};
console.log(person.completeName)
所以,我想创建一个函数来做一些事情,然后在稍后创建的不同对象中使用相同的函数。
下面的代码中有两个实例:测试(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
外面创建一个新的属性,同时使用调用把这个=人工作,但不在里面。
这些是我的问题:
- 如何在对象内部使用(调用)函数?
- 在对象内部调用函数,这是一种愚蠢的尝试吗?有没有更好的方法来完成同样的任务?
您可能想为此使用 getter。
function fullName() {
return this.firstName + " " + this.lastName;
}
const person = {
firstName: "Anant",
lastName: "Ghotale",
get completeName() {
return fullName.call(this)
}
};
console.log(person.completeName)