Если у меня есть объект с несколькими клавишами, вызывающими одну и ту же функцию, и эта функция реализована вне ее области, как определить, какая клавиша вызвала эту функцию? Например:
function tellYourAge() {
return function()
{
// I already know here that this refers to Population
// For example, console.info(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
}
🤔 А знаете ли вы, что...
JavaScript можно использовать для создания анимаций и игр на веб-страницах.
function tellYourAge() {
return function()
{
var s = new Error().stack;
if (s.includes('Mahdi')){
console.info('Age is 18');
}
else if (s.includes('Samuel')){
console.info('Age is 20');
}
else if (s.includes('Jon')){
console.info('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
Вы не объяснили Зачем, что вы не хотите «передавать параметр», или что точно требует не передавать параметр. Я предполагаю, что вы хотите сохранить динамическое возвращаемое целое число (или другое значение) в некотором смысле, специфичном для вашего контекста.
Вот как я мог бы предложить это сделать, хотя до сих пор не ясно, хорошая ли это идея:
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
}
Возможно
function tellYourAge() {
return function()
{
var f = arguments.callee;
var key = Object.keys(this).filter(key => this[key] === f)[0];
console.info(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
. Теперь вам нужно найти вызываемый экземпляр функции в объекте, и все готово.
Я понял, что ваш вопрос заключается в том, как я могу связать возраст человека с его именем. Я бы сделал это, создав объекты, описывающие людей. Каждый объект будет иметь два атрибута: имя и возраст.
Затем объекты (люди) будут храниться в массиве, который является населением.
// 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.info(person.name + " is " + person.age);
}