Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
if ('attachEvent' in document) // это явно лучше, чем глупая проверка на undefined
if (document.attachEvent == null) // или вот так можно
if (typeof document.attachEvent == 'function') // нам ведь нужна именно функция, да?
document.attachEvent надо проверять на undefined, а не на function? Чем проверка на undefined лучше, чем сравнение с null? И так далее.(function (undefined) {
var object = { foo: undefined };
console.log( typeof object.foo != 'undefined' ); // false - свойства нету? О.о
console.log( 'foo' in object ); // true - есть
console.log( {}.hasOwnProperty.call( object, 'foo' ) ); // true
})();
хотя сравнение с приведением типов с null тоже в данном случае сработает.
м
operator equals (left, right) {
if ( (isNull(left ) || isUndefined(left )) &&
(isNull(right) || isUndefined(right))) {
return true;
}
// тут проверяем типы и так далее
}
Рекомендуется он в соответствии с теорией, что сравнение без приведения типов (== vs ===) чуть быстрее по скорости.
if(!!null === !!document.attachEvent) ... // !! - самый короткий путь приведения к booleanif (typeof document.attachEvent == 'function')if ('attachEvent' in document)Лишняя операция в document.attachEvent == null, это полностью аналогично такому коду
if(!!null === !!document.attachEvent)
(function () {
var document = { attachEvent: false };
console.log( document.attachEvent == null ); // false
console.log( !!document.attachEvent == !!null ); // true
})();
console.log( !!document.attachEvent === !!null ); if (document.attachEvent == null) // или вот так можно var document = { attachEvent: false };
console.log( document.attachEvent == null ); // true
console.log( document.attachEvent1 == null ); // truedocument = { attachEvent: false };
console.log( !!document.attachEvent === !!null ); // true
console.log( !!document.attachEvent1 === !!null ); // true
document не переопределяется. Если сделаете console.log( document ), то поймёте в чём ваша ошибка. Я не зря оборачиваю код в анонимную функциюObject.defineProperty( window, 'document', {
configurable: false,
value: new Document()
});
(function () {
var obj = {};
Object.defineProperty( obj, 'test', { configurable: false, value: 1 });
obj.test = 2;
console.log( obj.test ); // 1
}());
(function () {
'use strict';
var obj = {};
Object.defineProperty( obj, 'test', { configurable: false, value: 1 });
obj.test = 2;
console.log( obj.test );
// Cannot assign to read only property 'test' of #<Object>
}());
(function () {
'use strict';
window.document = 1;
// Cannot assign to read only property 'document' of [object DOMWindow]
}());
(function (undefined) {
var count = 10000000, i;
console.time( 'typeof' );
for (i = count; i--;) (typeof undefined == 'undefined');
console.timeEnd( 'typeof' ); // 71
console.time( 'null' );
for (i = count; i--;) (undefined == null);
console.timeEnd( 'null' ); // 54
})();
(function () {
var count = 10000000, i;
console.time( 'typeof' );
for (i = count; i--;) (typeof undefined == 'undefined');
console.timeEnd( 'typeof' ); // 2334
console.time( 'null' );
for (i = count; i--;) (undefined == null);
console.timeEnd( 'null' ); // 2307
})();
if(document.attachEvent !== undefined)
document.attachEvent('onclick', someFn)(function(undefined){
console.log(windov === undefined);
})();Application.closure.apply(function(a, u, j, undefined){
//Эти сокращения хорошо задокументированны
//a - application
//u - underscore
//j - jQuery
});(function(undefined){
})();(function( window, undefined ) { // смотрим описание функции, второй параметр называется undefined
})( window ); // смотрим вызов этой функции, передан только один аргумент, значит тип второго будет действительно undefined
Application.closure.apply(function(a, u, j, undefined){ // здесь именно вызов функции, без контекста выглядит что undefined - это обычная переменная, и вы ее куда-то передаете. Выглядит как антипаттерн
//Эти сокращения хорошо задокументированны
//a - application
//u - underscore
//j - jQuery
});The typeof operator returns a string indicating the type of its operand. The
string returned is one of
• “undefined”
• “object”
• “function”
• “number”
• “boolean”
• “string”
The Undefined Type
Any variable that has not been assigned a value is automatically of type
undefined.
typeof a == 'undefined' — это согласно стандарту, а просто undefined — на совести разработчиков браузеров// regular
$(elem).data(key, value);
// OMG like 10x faster
$.data(elem, key, value);
Коллекция паттернов и антипаттернов JavaScript