简体   繁体   English

方法的javascript属性

[英]javascript properties of methods

Is it possible in javascript to set properties inside methods? 是否有可能在javascript中设置方法内部的属性?

For example 例如

function Main() {

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

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

I tried this and it logs 'undefined'. 我试过了,它记录为“未定义”。 Is it about scope? 关于范围吗?

Inside method() you're setting a property of the object on which the method is called rather than on the function object representing the method. method()内部,您要设置在其上调用方法的对象的属性,而不是在表示该方法的函数对象上的属性。

This shows the difference inside the 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
};

This shows the difference in accessing the property after the method is called 这表明在调用方法后访问属性的区别

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'

You should decide whether you need a property on the function object or on p object. 您应该决定是否需要函数对象或p对象上的属性。 Note that the function object may be shared by a number of objects created by the Main() constructor. 注意,函数对象可以由Main()构造函数创建的许多对象共享。 Hence it will behave in a manner somewhat similar to a static member in languages like C++ or Java. 因此,它的行为与类似于C ++或Java的静态成员的行为类似。

If you intend to use property defined on the object, your code should look similar to this: 如果打算使用在对象上定义的属性,则代码应类似于以下内容:

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.

If you intend to use a property defined on the function object representing method() , your code should look similar to this: 如果打算使用在表示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.

Functions are objects basically, so just set it like you get it: 函数基本上是对象,所以只要像得到它一样进行设置即可:

this.method = function() {

};

this.method.parameter = 'something_relevant';

Also, don't eliminate semicolons after expressions. 另外,不要在表达式后消除分号。

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

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