方法的 JavaScript 属性

标签 javascript oop

是否可以在 JavaScript 中设置方法内的属性?

例如

function Main() {

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

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

我尝试了这个,它记录了“未定义”。与范围有关吗?

最佳答案

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'

您应该决定是否需要函数对象或 p 对象上的属性。请注意,该函数对象可以由 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.

关于方法的 JavaScript 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8625202/

相关文章:

c# - 自动从对象内的其他属性分配属性值

javascript - 添加 tinymce 4 后,textarea 事件不起作用

javascript - Select2 本地分页/无限滚动

javascript - JavaScript/jQuery 中的嵌套循环不起作用

java - 指定合金中 Sig 的范围

PHP MVC : Data Mapper pattern: class design

javascript - CouchDB:将字段添加到 View 中的 "doc"

javascript - 单击 div 时更改复选框值

Javascript - 通过引用定义对象属性名称

Java 面向对象的类之间的函数调用