如果我有一个带有多个调用同一功能的键的对象,并且此功能在其范围之外实现,那么如何确定哪个键调用了此功能?例如:
function tellYourAge() {
return function()
{
// I already know here that this refers to Population
// For example, console.log(this) will print the Population object
}
}
{
let Population = {
Mahdi: tellYourAge(),
Samuel: tellYourAge(),
Jon: tellYourAge()
};
Population.Mahdi(); // It should log 18
Population.Samuel(); // It should log 20
Population.Jon(); // It should log 21
}
答案 0 :(得分:9)
可能
function tellYourAge() {
return function()
{
var f = arguments.callee;
var key = Object.keys(this).filter(key => this[key] === f)[0];
console.log(key);
}
}
{
let Population = {
Mahdi: tellYourAge(),
Samuel: tellYourAge(),
Jon: tellYourAge()
};
Population.Mahdi(); // prints Mahdi
Population.Samuel(); // prints Samuel
Population.Jon(); // prints Jon
}
说明:arguments.callee
引用arguments
对象所属的功能。并且this
基本上是函数调用时的“点之前的东西”,因此是Population
对象。现在,您要做的就是在对象中查找被调用的函数实例,然后完成操作。
答案 1 :(得分:1)
function tellYourAge() {
return function()
{
var s = new Error().stack;
if(s.includes('Mahdi')){
console.log('Age is 18');
}
else if(s.includes('Samuel')){
console.log('Age is 20');
}
else if(s.includes('Jon')){
console.log('Age is 21');
}
}
}
{
let Population = {
Mahdi: tellYourAge(),
Samuel: tellYourAge(),
Jon: tellYourAge()
};
Population.Mahdi(); // It should log 18
Population.Samuel(); // It should log 20
Population.Jon(); // It should log 21
}
Output:
Age is 18
Age is 20
Age is 21
仅供参考,新的Error()。stack将为您提供如下的堆栈跟踪信息,
Error
at Object.Samuel (<anonymous>:4:20)
at <anonymous>:1:19
答案 2 :(得分:1)
我理解您的问题是如何将一个人的年龄与其姓名相关联。我要做的方法是创建描述人的对象。每个对象将具有两个属性,即名称和年龄。
然后,将这些对象(人)存储在一个数组中,该数组即人口。
// Create a constructor function which defines a Person
function Person(name, age) {
this.name = name;
this.age = age;
}
// Create an array of Population to store the Persons (people)
var Population = [];
Population.push(new Person('Mahdi', 18));
Population.push(new Person('Samuel', 20));
Population.push(new Person('John', 21));
// Counter and limit variables
var i, l;
// Loop through the Population and display the information about the people
l = Population.length;
for (i = 0; i < l; i++) {
let person = Population[i];
console.log(person.name + " is " + person.age);
}
答案 3 :(得分:0)
您尚未说明为什么您不想“传递参数”,或者确切地不传递参数的要求是什么。我的猜测是,您希望在特定情况下使返回的整数(或其他值)保持动态。
这是我可能会建议这样做的方式,尽管尚不清楚这是否是一个好主意:
function tellYourAge() {
return function(name)
{
let ages = {
Mahdi: 18,
Samuel: 20,
Jon: 21,
};
return ages[name];
}
}
{
let makePopulation = function(names){
let pop = {};
names.forEach(function(n){
pop[n] = tellYourAge().bind(pop, n);
});
return pop;
};
let Population = makePopulation("Mahdi", "Samuel", "Jon");
Population.Mahdi(); // It should log 18
Population.Samuel(); // It should log 20
Population.Jon(); // It should log 21
}