简体   繁体   English

从javascript对象调用函数

[英]Calling a function from a javascript object

I have been using/calling functions from objects like this: 我一直在使用/从这样的对象中调用函数:

var object = { 
    fn: function(){ 
        alert('i can see it!'); 
    }
}; 
object.fn(); // it works

but I don't know how to call function from mere {} object. 但我不知道如何从仅{}对象调用函数。

{
    fn: function() {
        alert('i can\'t see it');
    }
}

fn(); // wont work ?

I want to know why this is not working? 我想知道为什么这不起作用? Is there a way to make it work? 有办法使它起作用吗?

Your second example is invalid syntax. 您的第二个示例是无效的语法。 The {} is interpreted as a block statement with a label and an invalid function because it has no name. {}被解释为带有标签和无效函数的语句,因为它没有名称。

If you wanted to do it inline like that, you'd need something more like this: 如果您想这样内联,则需要更多类似以下内容:

({
    fn: function() {
        alert('now i can see it');
    }
}).fn();

Now you're creating an object since the {} can no longer be a block statement, but is instead object literal syntax. 现在,您正在创建对象,因为{}不再是块语句,而是对象文字语法。 Then you're immediately accessing the fn property you defined. 然后,您立即访问定义的fn属性。

Of course there's little point to this, but it's closer to what you were doing. 当然,这没有什么意义,但是它更接近您的工作。

fn is inside the blocks and not inside the object. fn在块内,而不在对象内。 Passing name-value just inside blocks ie {} dont work. 仅在块内传递名称值,即{}不起作用。 Or atleast give some label to the block. 或至少给标签加上一些标签。

Call it like so: object.fn(); 这样称呼它: object.fn(); . As @BlueSkies said, the second example will not work, as it is invalid syntax. 正如@BlueSkies所说,第二个示例将无效,因为它的语法无效。 You can't do that in JavaScript. 您无法在JavaScript中做到这一点。 If you name that object like David said in the comments, then it will work. 如果像大卫在评论中说的那样命名该对象,则它将起作用。 You can't call a function out of an anonymous object. 您不能从匿名对象中调用函数。

Here is an example with the object being called e : http://jsfiddle.net/dhF5k/ 这是一个名为e的对象的示例: http : //jsfiddle.net/dhF5k/

Here is the proper syntax to define a "standalone" function (with no wrapper object) : 这是定义“独立”功能(没有包装对象)的正确语法:

var fn = function () { ... };
function fn() { ... };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM