>  기사  >  웹 프론트엔드  >  Function.prototype.bind 사용법 example_javascript 기술

Function.prototype.bind 사용법 example_javascript 기술

WBOY
WBOY원래의
2016-05-16 17:22:36941검색
코드 복사 코드는 다음과 같습니다.

//ECMAScript 5 Function.prototype.bind 함수 호환성 처리
(function(){
if ( !Function.prototype.bind ) { //function(){}.bind
Function.prototype.bind = function ( o, /*매개변수 목록*/ ) {
var self = this,boundArgs = Array.prototype.slice.call(arguments, 0);
return function(){
var args = [], i = 1; i for ( i = 0; i return this.apply(o, args);
}
}
}
})()


사용 예:
1. 호출 예시


/*예제 1*/
function f1(y , z){ return this.x y z;}
//Call 1
var g1 = f1.bind({x:1}, 2) //this.x = 1; y = 2;
console.loog( g1(3) ); //this.x y 3 = 6
//2 호출
var g2 = f1.bind({x:1}); //this.x = 1;
console.log( g2(2,3) ); //this.x 2 3 = 6

/*예제 2*/
var f2( x, y){ return x y; }
//
호출 var g3 = f2.bind(null, 1) //x = 1
console.log( g3(2) ) // x 2 = 3


2. DOM 호출 예시


var eleBtn = document.getElementById("button")
, eleText = document.getElementById("text")

eleBtn.onclick = function(color) {
color = color || " #003399";
this.style.color = color; //이때 eleText를 가리킵니다.
}.bind(eleText, "#cd0000"); >
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.