>  기사  >  웹 프론트엔드  >  javascript 바인드 바인딩 함수 code_javascript 기술

javascript 바인드 바인딩 함수 code_javascript 기술

WBOY
WBOY원래의
2016-05-16 18:37:21803검색

구체적인 결론은 "Javascript의 동적 this 및 동적 바인딩 예제 코드"를 참조하세요. 이 기사에서는 비침입적 바인딩 기능 설계에 중점을 둡니다.


[Ctrl A 모두 선택 참고: 외부 J를 도입해야 하는 경우 실행하려면 새로 고쳐야 합니다.
]

기반 기본 객체를 확장하지 않을 경우 원칙적으로 이 바인드 함수를 만들었으며(dom은 범위임) 사용법은 Prototype 프레임워크의 바인드와 유사합니다. 코드는 다음과 같습니다.


dom.bind = function(fn,context ){
//원한다면 두 번째 매개변수도 thisObject,scope,
로 변경할 수 있습니다//간단히 말하면 새로운 범위 객체입니다
if (arguments.length < 2 && context == =정의되지 않음) return fn;
var 메소드 = fn,
slice = Array.prototype.slice,
args = Slice.call(arguments, 2)
return function(){/ /여기에 원본 fn의 매개변수를 전달합니다.
var array = Slice.call(arguments, 0)
method.apply(context,args.concat(array))
}


사용법: 첫 번째 매개변수는 범위에 바인딩해야 하는 함수이고, 두 번째 매개변수는 창이나 다양한 개체이며, 기타 매개변수는 선택사항입니다.

[Ctrl A 모두 선택 참고:
외부 J를 도입해야 하는 경우 실행하려면 새로 고쳐야 합니다.
]
또 다른 예:
[Ctrl A 모두 선택 참고: <script> window.name = "the window object" function scopeTest() { return this.name } // calling the function in global scope: scopeTest() // -> "the window object" var foo = { name: "the foo object!", otherScopeTest: function() { return this.name } } foo.otherScopeTest() // -> "the foo object!" </script>외부 J를 도입해야 하는 경우 실행하려면 새로 고쳐야 합니다 <script> dom = {}; dom.bind = function(fn,context){ if (arguments.length < 2 && context===undefined) return fn; var method = fn, slice = Array.prototype.slice, args = slice.call(arguments, 2); return function(){//这里传入原fn的参数 var array = slice.call(arguments, 0); method.apply(context,args.concat(array)) } } window.name = 'This is window'; var jj = { name: '这是jj', alertName: function() {//绑定失效 alert(this.name); } }; var kk = { name:"kkです" } function run(f) { f(); } run(jj.alertName); var fx2 = dom.bind(jj.alertName,jj) run(fx2); var fx3 = dom.bind(jj.alertName,window) run(fx3); var fx4 = dom.bind(jj.alertName,kk) run(fx4); </script>]<script> dom = {}; dom.bind = function(fn,context){ if (arguments.length < 2 && context===undefined) return fn; var method = fn, slice = Array.prototype.slice, args = slice.call(arguments, 2); return function(){//这里传入原fn的参数 var array = slice.call(arguments, 0); method.apply(context,args.concat(array)) } } var obj = { name: 'A nice demo', fx: function() { alert(this.name + '\n' + Array.prototype.slice.call(arguments,0).join(', ')); } }; var fx2 = dom.bind(obj.fx,obj, 1, 2, 3); fx2(4, 5); // Alerts the proper name, then "1, 2, 3, 4, 5" </script>
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.