신경 안 쓰는 사이에 거의 모든 브라우저가 ECMAScript 5를 지원하게 되는 황금기를 맞는군요. NodeJS에서 다른 사람이 짠 코드를 참고할 때 종종 보이던 ES5의 새 기능을 눈여겨 두었다가 드문드문 써먹곤 했었는데 이제 정말로 깨우치고 사용해야 할 시기라는 생각이 듭니다. 다음은 MDN에서 퍼온 자바스크립트 1.8에서 추가된 기능과 설명입니다.
/* Object */
Object.create // Creates a new object with the specified prototype object and properties.
Object.defineProperty // Adds the named property described by a given descriptor to an object.
Object.defineProperties // Adds the named properties described by the given descriptors to an object.
Object.getPrototypeOf // Returns a property descriptor for a named property on an object.
Object.keys // Returns an array of all enumerable properties on an object.
Object.preventExtensions // Prevents any extensions of an object.
Object.seal // Prevents other code from deleting properties of an object.
Object.isSealed // Determine if an object is sealed.
Object.freeze // Freezes an object: other code can't delete or change any properties.
Object.isFrozen // Determine if an object was frozen.
Object.isExtensible // Determine if extending of an object is allowed.
Object.getOwnPropertyDescriptor //Returns a property descriptor for an own property of a given object.
Object.getOwnPropertyNames // Returns an array of all enumerable and non-enumerable properties on an object.
/* Array */
Array.isArray // Checks if a variable is an array.
Array.prototype.indexOf // Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
Array.prototype.lastIndexOf // Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
Array.prototype.every // Returns true if every element in this array satisfies the provided testing function.
Array.prototype.some // Returns true if at least one element in this array satisfies the provided testing function.
Array.prototype.forEach // Calls a function for each element in the array.
Array.prototype.map // Creates a new array with the results of calling a provided function on every element in this array.
Array.prototype.filter // Creates a new array with all of the elements of this array for which the provided filtering function returns true.
Array.prototype.reduce // Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
Array.prototype.reduceRight // Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
/* More */
Function.prototype.bind // Creates a new function that, when called, itself calls this function in the context provided
String.prototype.trim // Removes whitespace from both ends of the string.
Date.prototype.toJSON // Returns a string encapsulating the Date object in JSON format.
Date.prototype.toISOString // JavaScript provides a direct way to convert a date object into a string in ISO format.
Date.now // Returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
"use strict" // strict mode support
Object
와 Array.prototype
에 새로운 기능들이 대거 추가되었습니다. 특히, Object.keys
는 정말 유용하게 사용될 거 같습니다. 인자로 받은 options을 default options과 머지할 때 아주 유용하겠네요. 자바스크립트는 배열과 관련된 메서드들이 정말 부실했었는데, indexOf
, forEach
, map
, filter
, reduce
, some
등 전부 요긴하게 사용할 수 있는 녀석들이 뭉탱이로 들어와 있습니다. 또한 Function.prototype.bind
이 추가되어 별다른 트릭없이 선호하는 문법을 구사할 수 있게 되었습니다. 아무리 생각해도 var self = this
와 같은 문장은 언어적 결함으로밖에 보이지 않거든요. 다음은 자주 사용될 것 같은 코드 스니펫들입니다.
/* Basic Class */
var book={ title: 'default', author: 'default' };
var techBook=Object.create(book, {category: {value: 'technology'}});
techBook.category; //=> technology
Object.defineProperty(techBook, "category", {value: 'javascript'});
techBook.category; //=> javascript
/* Mixin Class */
function MyClass() {
SuperClass.call(this);
OtherSuperClass.call(this);
}
MyClass.prototype = Object.create(SuperClass.prototype); //inherit
mixin(MyClass.prototype, OtherSuperClass.prototype); //mixin
MyClass.prototype.myMethod = function() {
// do a thing
};
/* Object extend */
Object.keys(options).forEach(function(key){
form[key] = options[key];
});
/* Getter/Setter */
var myObject = {};
Object.defineProperty( myObject, '_myProp', {
value: 'myDefault',
writable: false,
enumberable: false,
configurable: true
});
Object.defineProperty( myObject, 'myProp', {
enumberable: true,
configurable: true,
set: function( v ) {
Object.defineProperty( this, '_myProp', { writable:true } );
this._myProp = v;
Object.defineProperty( this, '_myProp', { writable:false } );
},
get: function() {
return this._myProp;
}
});
alert( myObject.myProp );
myObject.myProp = 'myValue';
alert( myObject.myProp );
myObject._myProp = 'teehee, not writable';
alert( myObject._myProp );
/* non-writable */
var o = {}; // Creates a new object
Object.defineProperty(o, "a", { value : 37, writable : false });
o.a = 25; // No error thrown (it would throw in strict mode)
o.a //=> 37
/* Fu*k self */
function LateBloomer() {
this.petalCount = Math.ceil( Math.random() * 12 ) + 1;
}
// declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
window.setTimeout( this.declare.bind( this ), 1000 );
};
LateBloomer.prototype.declare = function() {
console.log('I am a beautiful flower with ' + this.petalCount + ' petals!');
};
/* ISODateString */
new Date().toISOString() //=> "2012-12-01T20:24:27.681Z"
/* Real trim */
" _firejune ".trim() //=> "_firejune"
하위 호환을 위한 폴리필(Polyfill) 라이브러리로는 ES5-Shim이 대세인 듯 합니다.
Comments
Got something to add? You can just leave a comment.
자바스크립트 1.8.5(ES5)의 새 기능: 신경 안 쓰는 사이에 거의 모든 브라우저가 ECMAScript 5를 지원하게 되는 황금기를 맞는군요. NodeJS에서 다른 사람이 짠 코드를 참고할 때 종종... http://t.co/F0Pikel6
from twitterfeed
RT @firejune: 자바스크립트 1.8.5(ES5)의 새 기능 firejune.com/1772
from twitter
RT @firejune: 자바스크립트 1.8.5(ES5)의 새 기능 firejune.com/1772
from twitter
RT @firejune: 자바스크립트 1.8.5(ES5)의 새 기능 firejune.com/1772
from twitter
RT @firejune: 자바스크립트 1.8.5(ES5)의 새 기능 firejune.com/1772
from twitter
RT @firejune: 자바스크립트 1.8.5(ES5)의 새 기능 firejune.com/1772
from twitter
RT @firejune: 자바스크립트 1.8.5(ES5)의 새 기능 firejune.com/1772
from twitter
RT @firejune: 자바스크립트 1.8.5(ES5)의 새 기능 firejune.com/1772
from twitter
[경준호] 자바스크립트 1.8.5(ES5)의 새 기능: 신경 안 쓰는 사이에 거의 모든 브라우저가 ECMAScript 5를 지원하게 되는 황금기를 맞는군요. NodeJS에서 다른 사람이 짠 코드를 참고... http://t.co/B71dY40d
from twitterfeed
RT @beyonditblog: 자바스크립트 1.8.5(ES5)의 새 기능: 신경 안 쓰는 사이에 거의 모든 브라우저가 ECMAScript 5를 지원하게 되는 황금기를 맞는군요. NodeJS에서 다른 사람이 짠 코드를 참고할 때 종종... http://t.co/F0Pikel6
from twitter
RT @firejune: 자바스크립트 1.8.5(ES5)의 새 기능 http://t.co/ebr6BJeP
from twitter
“@firejune: 자바스크립트 1.8.5(ES5)의 새 기능 http://t.co/KXK1BU16” filter, reduce, bind,... 오호라~~~
from twitter
자바스크립트 1.8.5(ES5)의 새 기능 - Firejune http://t.co/QNNBXbk9
from chrome-share
Your Reaction Time!