Javascript 方法的不同可访问性取决于其声明方式

Javascript 方法的不同可访问性取决于其声明方式,javascript,oop,methods,Javascript,Oop,Methods,在这里刷新我的Javascript知识,让我知道这是该语言的基础。在我的例子中,我可以看到发生了什么,但我无法用语言表达原因。我还添加了Chrome控制台分解对象视图 问题: Example = {} Example.MyExample = {} Example.MyExample.Person = function(name, age, gender) { this.name = name; this.age = age; this.gender = gender;

在这里刷新我的Javascript知识,让我知道这是该语言的基础。在我的例子中,我可以看到发生了什么,但我无法用语言表达原因。我还添加了Chrome控制台分解对象视图

问题:

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
我所声明的MyMethod1MyMethod2在可访问性方面的区别是什么

a)示例.MyExample.Person对象和

b)对于p,是示例.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
镀铬分解对象视图:

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

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

new SomeClass() !== SomeClass;
Example.MyExample.Person.MyMethod2();
现在,您已经将
MyMethod2
指定为构造函数本身的属性。因此,要访问
MyMethod2
,必须使用构造函数:

new SomeClass() !== SomeClass;
Example.MyExample.Person.MyMethod2();
然而,
MyMethod1
被分配(重新定义)给调用
Person
使用
new
返回的每个对象。因此,您必须获取该类的实例才能访问
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、它的一个实例和我声明这两个方法的方式之间的明确区别的词。谢谢