program story

Javascript에서 동적으로 이름이 지정된 메서드를 어떻게 호출합니까?

inputbox 2020. 8. 26. 07:51
반응형

Javascript에서 동적으로 이름이 지정된 메서드를 어떻게 호출합니까?


나는 웹 페이지가 구성 될 때 삽입 될 자바 스크립트를 동적으로 만드는 작업을하고 있습니다.

Javascript는 다른 목록 상자의 선택에 따라 목록 상자를 채우는 데 사용됩니다. 하나의 목록 상자의 선택이 변경되면 목록 상자의 선택한 값에 따라 메서드 이름이 호출됩니다.

예를 들면 :

Listbox1에는 다음이 포함됩니다.

색상
모양

'Colours'가 선택되면 다른 목록 상자를 채우는 "populate_Colours"메소드를 호출합니다.
내 질문을 명확히하기 위해 Javascript에서 "populate_Colours"호출을 어떻게 만듭니 까?


'populate_Colours'메소드가 전역 네임 스페이스에 있다고 가정하면 다음 코드를 사용할 수 있습니다.이 코드는 모든 객체 속성이 마치 연관 배열 인 것처럼 액세스 할 수 있고 모든 전역 객체가 실제로 window호스트 객체의 속성이라는 점을 모두 활용 합니다. .

var method_name = "Colours";
var method_prefix = "populate_";

// Call function:
window[method_prefix + method_name](arg1, arg2);

Triptych가 지적했듯이 호스트 개체의 내용에서 모든 전역 범위 함수를 찾아 호출 할 수 있습니다.

전역 네임 스페이스를 훨씬 덜 오염시키는 더 깨끗한 방법은 다음과 같이 함수를 배열에 직접 명시 적으로 넣는 것입니다.

var dyn_functions = [];
dyn_functions['populate_Colours'] = function (arg1, arg2) { 
                // function body
           };
dyn_functions['populate_Shapes'] = function (arg1, arg2) { 
                // function body
           };
// calling one of the functions
var result = dyn_functions['populate_Shapes'](1, 2);
// this works as well due to the similarity between arrays and objects
var result2 = dyn_functions.populate_Shapes(1, 2);

이 배열은 전역 호스트 객체가 아닌 다른 객체의 속성 일 수도 있습니다. 즉, jQuery와 같은 많은 JS 라이브러리가 수행하는 것처럼 자신 만의 네임 스페이스를 효과적으로 만들 수 있습니다. 이는 동일한 페이지에 여러 개의 개별 유틸리티 라이브러리를 포함 할 때 충돌을 줄이는 데 유용하며 (디자인의 다른 부분이 허용하는 경우) 다른 페이지에서 코드를 더 쉽게 재사용 할 수 있습니다.

다음과 같은 객체를 사용할 수도 있습니다.

var dyn_functions = {};
dyn_functions.populate_Colours = function (arg1, arg2) { 
                // function body
           };
dyn_functions['populate_Shapes'] = function (arg1, arg2) { 
                // function body
           };
// calling one of the functions
var result = dyn_functions.populate_Shapes(1, 2);
// this works as well due to the similarity between arrays and objects
var result2 = dyn_functions['populate_Shapes'](1, 2);

배열이나 객체를 사용하여 함수를 설정하거나 액세스하는 방법을 사용할 수 있으며 물론 다른 객체도 거기에 저장할 수 있습니다. 다음과 같이 JS 리터럴 표기법을 사용하여시나 믹이 아닌 상수에 대한 두 메서드의 구문을 더 줄일 수 있습니다.

var dyn_functions = {
           populate_Colours:function (arg1, arg2) { 
                // function body
           };
         , populate_Shapes:function (arg1, arg2) { 
                // function body
           };
};

Edit: of course for larger blocks of functionality you can expand the above to the very common "module pattern" which is a popular way to encapsulate code features in an organised manner.


I would recommend NOT to use global / window / eval for this purpose.
Instead, do it this way:

define all methods as properties of Handler:

var Handler={};

Handler.application_run = function (name) {
console.log(name)
}

Now call it like this

var somefunc = "application_run";
Handler[somefunc]('jerry');

Output: jerry


you can do it like this:

function MyClass() {
    this.abc = function() {
        alert("abc");
    }
}

var myObject = new MyClass();
myObject["abc"]();

Within a ServiceWorker or Worker, replace window with self:

self[method_prefix + method_name](arg1, arg2);

Workers have no access to the DOM, therefore window is an invalid reference. The equivalent global scope identifier for this purpose is self.


Hi try this,

 var callback_function = new Function(functionName);
 callback_function();

it will handle the parameters itself.


Here is a working and simple solution for checking existence of a function and triaging that function dynamically by another function;

Trigger function

function runDynmicFunction(functionname){ 

    if (typeof window[functionname] == "function"  ) { //check availability

        window[functionname]("this is from the function it "); //run function and pass a parameter to it
    }
}

and you can now generate the function dynamically maybe using php like this

function runThis_func(my_Parameter){

    alert(my_Parameter +" triggerd");
}

now you can call the function using dynamically generated event

<?php

$name_frm_somware ="runThis_func";

echo "<input type='button' value='Button' onclick='runDynmicFunction(\"".$name_frm_somware."\");'>";

?>

the exact HTML code you need is

<input type="button" value="Button" onclick="runDynmicFunction('runThis_func');">

Try with this:

var fn_name = "Colours",
fn = eval("populate_"+fn_name);
fn(args1,argsN);

참고URL : https://stackoverflow.com/questions/969743/how-do-i-call-a-dynamically-named-method-in-javascript

반응형