2011-12-24 58 views
0

是否有可能在JavaScript中设置方法内的属性?方法的javascript属性

例如

function Main() { 

    this.method = function() { 
     this.parameter = 'something_relevant' 
    } 
} 

var p = new Main() 
p.method() 
console.log(p.method.parameter) 

我尝试这样做,它记录 '未定义'。它是关于范围的吗?

+0

那是因为你'method'调用是异步的,如果你把里面的''console.log'的this.method'分配后它会奏效。 – Cyclonecode 2011-12-24 14:58:19

+0

@Krister Andersson:真的,这里没什么异步。 – pimvdb 2011-12-24 15:00:50

回答

3

Inside method()您正在设置调用方法的对象的属性,而不是表示方法的函数对象。

这表明里面的方法的区别是:

this.method = function() { 
    this.parameter = 'abc'; // Set parameter on the object on which method() is called 
    this.method.parameter = 'xyz'; // Set parameter on the object representing the method itself 
}; 

这表明在访问属性的不同方法被调用

p.method(); 
console.log(p.parameter); // Display property of the object p, equals 'abc' 
console.log(p.method.parameter); // Display property of the function object representing method(), equals 'xyz' 

后,您应该决定是否需要对功能特性对象或对象。请注意,函数对象可能由Main()构造函数创建的许多对象共享。因此,它的行为方式与C++或Java等语言中的静态成员有些类似。

如果您打算使用对象上定义的属性,你的代码应该类似于此:

function Main() { 

    this.method = function() { 
     this.parameter = 'something_relevant'; // Set property on object on which method() is called. 
    }; 
} 

var p = new Main(); 
p.method(); 
console.log(p.parameter); // Read property from object p. 

如果您打算使用代表method()函数对象上定义的属性,你的代码应该类似于为此:

function Main() { 

    this.method = function() { 
     this.method.parameter = 'something_relevant'; // Set property on function object representing method(). 
    }; 
} 

var p = new Main(); 
p.method(); 
console.log(p.method.parameter); // Read property from the function object. 
+0

谢谢你延长你的回答,基本上我需要一个描述方法的属性,所以我可以说它与'class'有关(请原谅这个词一个JavaScript上下文) – fatmatto 2011-12-24 15:27:19

2

函数是对象基本上,所以只是把它就像你得到它:

this.method = function() { 

}; 

this.method.parameter = 'something_relevant'; 

而且,表情后不排除分号。

+0

谢谢你,对不起分号,我在发帖的时候忘了他们 – fatmatto 2011-12-24 15:10:57