var Type = {};
for (var i = 0, type; type = ['String', 'Array', 'Number'][i++];) {
(function(type) {
Type['is' + type] = function(obj) {
console.info(obj)
return Object.prototype.toString.call(obj) === '[object ' + type + ']';
}
})(type);
}
console.info(Type.isArray([]))
console.info(Type.isString('str'))Очень смущен, почему «obj» равен «type»
Добро пожаловать в СО! Пожалуйста, ознакомьтесь с этим: Как создать минимальный, полный и проверяемый пример — вы отлично поработали над минимальной и полной частями, но, поскольку ваш код на самом деле ничего не делает, над проверяемой частью нужно доработать. Пожалуйста, приведите правильно написанный пример. Например, ваш цикл for имеет только два аргумента, когда вы пытаетесь увеличить свой счетчик в «тесте», а не в инкрементаторе. Непонятно, чего вы пытаетесь добиться.
Большое спасибо за ответ. Например, когда я вызываю Type.isArray([]), когда функция выполняется для Type [is'+ type +'] = function(obj){}, я не понимаю, почему значение obj будет "type".



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Смотрите комментарии в коде
var Type = {};
// This is like
// types = ['String', 'Array', 'Number'];
// for (var i = 0; i < types.lenght; i++) {
// var type = types[i];
// // ...
// }
// type = undefined;
for (var i = 0, type; type = ['String', 'Array', 'Number'][i++];) {
// This is like
// var closure = function(type) {
// // ...
// };
// closure(type)
(function(type) {
// The global object 'Type' is getting a new element which is a function.
// This element has a name which consists of the prefix 'is'
// and the value of the varaible 'type'
// ('String', 'Array', or 'Number')
// So after the for loop Type will have functions 'isString', 'isArray' ,and 'isNumber'
// 'obj' will store the parameter that the function is called with
// for example: Type.isArray([1,2,3]) will store [1,2,3] with the variable obj
Type['is' + type] = function(obj) {
// Since this is a function inside of a function,
// the variable 'type' is known inside this (inner) function
// with the value it has at the time the outer was called
// (@see JavaScript closures)
console.info('type', type, 'obj', obj)
// This is a little trick. The `toString()` method of arrays, strings, and numbers outputs the contents of these objects. The same method of an object returns '[object Object]'
// Here we bend that `toString` method of the object 'class' to be called from within
// our Array, String, or Number and get what we need
//
// Why don't just use `typeof` operator? Because `typeof [] === 'object'`
//
// This will return true, if the String representation of 'obj'
// fits type
return Object.prototype.toString.call(obj) === '[object ' + type + ']';
}
})(type);
// This was called three times
// Type has now three new elements: 'isString', 'isArray', 'isNumber', all being functions
}
console.info(Type.isArray([]))
console.info(Type.isString('str'))
console.info(typeof [])Возможно, вы сталкивались с синтаксисом создания и доступа к объектам, поскольку есть два способа доступа к значениям, назначенным ключам объектов.
// They all overwrite the value of assigned to the key `myKey`
var key='Key';
myObj = {myKey: 'literal object initializer', unchanged: 'This value will remain unchanged in this example'};
console.info(myObj)
myObj.myKey = 'object access operator; dot notation';
console.info(myObj)
myObj['myKey'] = 'object access operator; brackets notation';
console.info(myObj)
myObj['my' + 'Key'] = 'object access operator; brackets notation with string concatenation';
console.info(myObj)
myObj['my' + key] = 'object access operator; brackets notation with string concatenation and variable interpolation';
console.info(myObj)См. документацию по MDM на Объекты и свойства.
«Очень запутался, почему 'obj' равен 'type'» — вы никогда не вызываете функцию, использующую
obj, так что… это не так, по крайней мере, в коде, которым вы с нами поделились.