简体   繁体   English

如何在javascript中引用函数对象的成员?

[英]How to refer to members of a function object in javascript?

I'm trying to do something like this: 我正在尝试做这样的事情:

function foo() { alert(this.bar); }
foo.bar = "Hello world";
foo();

That doesn't work because I believe this refers to the global object ( window ) rather than foo . 那是行不通的,因为我相信this是指全局对象( window )而不是foo How do I make it work? 我该如何运作?

this refer to the object used to call the method. this是指用于调用方法的对象。 By default, it will be the window object. 默认情况下,它将是window对象。

In your case, you should get the parameter in the function object directly using the named function as it is available in the scope. 在您的情况下,应该使用命名函数直接在函数对象中获取参数,因为它在范围中可用。

function foo() { alert(foo.bar); }
foo.bar = "Hello world";
foo();

You shouldn't use this as doing something like this: 您不应该使用this来做这样的事情:

foo.call({})

this will be equal to the empty object. this将等于空对象。

Possibly try using prototype : 可能尝试使用prototype

 function foo() { alert(this.bar); } foo.prototype.bar = "Hello world"; new foo(); //new object 

Recommended option: 推荐选项:

 function foo(bar) { //constructor argument this.bar = bar; } foo.prototype.getBar = function() { alert(this.bar); }; new foo("Hello world").getBar(); 

I'd choose to do it this way, as it makes use of the prototype chain. 我会选择这种方式,因为它利用了原型链。

function Foo() { return (this===window) ? new Foo() : this; }
Foo.prototype.hi = function() { alert(this.bar) };
Foo.prototype.bar = "Hi!";

var tmp = new Foo();
tmp.hi();

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

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