【问题标题】:Different accessibility of method based on how it is declared基于声明方式的方法的不同可访问性
【发布时间】:2018-04-23 19:13:57
【问题描述】:

在这里刷新我的 Javascript 知识,以便我知道这是该语言的基础知识。在我的示例中,我可以看到正在发生的事情,但我无法说出原因。我还添加了 Chrome 控制台分解对象视图。

问题:

的情况下,我声明 MyMethod1MyMethod2 的方式与可访问性有什么区别?

a) Example.MyExample.Person 对象和

b) 代表 pExample.MyExample.Person 的一个实例?

代码:

Example = {}
Example.MyExample = {}
Example.MyExample.Person = function(name, age, gender)
{
    this.name = name;
    this.age = age;
    this.gender = gender;
    this.MyMethod1 = function(){alert("My Method 1");}
};
Example.MyExample.Person.MyMethod2 = function(){alert("My Method 2");}

var p = new Example.MyExample.Person("tom", 78, "m");

p.MyMethod1(); // My Method 1
p.MyMethod2(); // p.MyMethod2 is not a function
Example.MyExample.Person.MyMethod1; // Example.MyExample.Person.MyMethod1 is not a function
Example.MyExample.Person.MyMethod2(); // My Method 2

Chrome 分解对象视图:

【问题讨论】:

    标签: javascript oop methods


    【解决方案1】:

    构造函数每次使用new 调用时都会返回一个新对象。它只是帮助设置新对象的属性值。新对象不等于构造函数:

    new SomeClass() !== SomeClass;
    

    现在,您已将MyMethod2 分配为构造函数本身的属性。所以要访问MyMethod2,你必须使用构造函数:

    Example.MyExample.Person.MyMethod2();
    

    然而,MyMethod1 被分配(重新定义)给使用new 调用Person 返回的每个对象。所以你必须获得一个类的实例才能访问MyMethod1。更多:

    var p1 = new Example.MyExample.Person();
    var p2 = new Example.MyExample.Person();
    
    p1.MyMethod1 !== p2.MyMethod1;  // because each time the constructor function get called MyMethod1 get redifined (they can be equal if they are attached to the prototype instead)
    

    MyMethod2 就是所谓的静态方法

    【讨论】:

    • "现在,您已将 MyMethod2 指定为构造函数本身的属性。" - 这些是我正在寻找的词来描述Example.MyExample.Person(它的一个实例)与我声明这两种方法的方式之间的明显区别。谢谢。
    猜你喜欢
    • 2012-12-04
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 2014-06-08
    • 2012-12-12
    • 1970-01-01
    相关资源
    最近更新 更多