在对象中调用javascript动态方法 [英] Call javascript dynamic method in object

查看:71
本文介绍了在对象中调用javascript动态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用以下两种方法创建一个类:

If I create a Class with two method like following:

var Car = function() {}
Car.prototype = {
    run: function() {
        alert('run');
    },
    stop: function() {
        alert('stop');
    }
}

当DOM准备好后,将调用test()方法,

和这个test()方法将创建一个Car实例并调用Car的方法

And when the DOM is ready will call test() method,
and this test() method will create a instance of Car and call the method of Car

$(document).ready(function() {
    test("run");
});
function test(method) {
    var instance = new Car();
    // call instance.run()
}

我知道我有使用apply()方法,

但是我已经尝试了很多次并且失败了

所以,我怎样才能在Object中使用apply()方法?

I know I have to use apply() method,
but I have tried lots of times and failed
So, how can I use apply() method in Object?

推荐答案

javascript中的对象是一个关联数组,因此您可以使用 [] 运算符通过字符串地址对象的任何成员,也起作用。

An object in javascript is an associative array, so you can use the [] operator to address by string any member of the object, functions as well.

function test(method) {
    var instance = new Car();
    instance[method]();
}

这将允许在对象Car上按名称调用函数。

this will allow to call a function by name over the object Car.

看到它在JsFiddle上工作

被调用方法中的上下文将正确地指向新创建的Car实例而不需要任何额外的努力,我想这就是你想要的。使用 apply 调用通常用于需要更改默认的' this '其他价值。

The context inside the called method will properly point to the newly created Car instance without any additional effort, that I guess is what you want. Using apply or call is generally used when you need to change the default 'this' value to something else.

这篇关于在对象中调用javascript动态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆