fn 을 다른 기능의 기능 매개 변수로 어떻게 사용할 수 있습니까? 또한 fn 매개 변수에는 자체 매개 변수가 있습니다. 등을 test("b('aa')")
, 어떻게 할까?
자바 스크립트
<script type="text/javascript">
function test(fn){
if(fn){
fn();
}
}
function a(){
alert(1);
}
function b(x){
alert(x);
}
/*
when click I get errors => TypeError: fn is not a function
*/
</script>
HTML
<button onclick="test('a')">test('a')</button>
<button onclick="test('b(hello)')">test('b(hello)')</button>
간단히 작성하십시오.
<script type="text/javascript">
function test(fn,parameter){
if(fn){
fn.apply(window,parameter||[]);
}
}
function a(){
alert(1);
}
function b(x){
alert(x);
}
/*
when click I get errors => TypeError: fn is not a function
*/
</script>
<button onclick="test(a)">test('a')</button>
<button onclick="test(b,['hello'])">test('b(hello)')</button>
Felix Kling의 의견에 감사드립니다. 여기에 설명이 있습니다.
'b (hello)'는 문자열 객체이기 때문에 정확 하지 않습니다 .
test('b("hello")')
당신이 얻는 것은 실제로 정의되지 않은 b ( 'hello')의 반환 값이기 때문에 정확 하지 않습니다.
test(b('hello'))
매개 변수를 기능 테스트로 보내려면 fn과 매개 변수를 분리해야합니다.
Function.prototype.apply ( thisValue , argumentsList )를 사용할 수 있습니다 .
내가 쓴대로
fn.apply(window,parameter||[])
이 FN 함수의 값은 기본값으로 창입니다.
parameter
<button>test('b(hello)')</button>
요소 에서 [ 'hello'] 인 인수 목록입니다 . ||[]
정의되지 않은 변수를 방지합니다. test(a)
인수가 구현되지 않은 예입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다