javascript面向对象程序设计之浅谈2

公有实例成员函数及私有实例成员函数的定义

<script type="text/javascript">

class2 = function() {

// private fields

var m_first = 1;

var m_second = 2;

// private methods

function method1() {    

alert(m_first);

}

var method2 = function() {

alert(m_second);

}

// public fields

this.first = "firsts";

this.second = ['s','e','c','o','n','d'];

// public methods

this.method1 = method2;

this.method2 = function() {

alert(this.second);

}

// constructor

{

//method1();

//method2();

}

}

// public method

class2.prototype.method3 = function() {

alert(this.first);

}

alert("----------------分割条------------------")

var o = new class2();

o.method1();

o.method2();

o.method3();

alert(o.first);

</script>

创建公有实例成员其实很简单,一种方式是通过在类中给 this.memberName来赋值,如果值是函数之外的类型,那就是个公有实例字段,如果值是函数类型,那就是公有实例方法。另外一种方式则是通过给 className.prototype.memberName 赋值,可赋值的类型跟 this.memberName 是相同的。

到底是通过 this 方式定义好呢,还是通过 prototype 方式定义好呢?

其实它们各有各的用途,它们之间不是谁比谁更好的关系。在某些情况下,我们只能用其中特定的一种方式来定义公有实例成员,而不能够使用另一种方式。原因在于它们实际上是有区别的:

1、prototype 方式只应该在类外定义。this 方式只能在类中定义。

2、prototype 方式如果在类中定义时,则存取私有实例成员时,总是存取最后一个对象实例中的私有实例成员。

3、prototype 方式定义的公有实例成员是创建在类的原型之上的成员。this 方式定义的公有实例成员,是直接创建在类的实例对象上的成员。

基于前两点区别,我们可以得到这样的结论:如果要在公有实例方法中存取私有实例成员,那么必须用 this 方式定义.

http://www.cftea.com/c/2008/01/AIA7FNJOHGH3QHFB.asp

原文请见:

原文地址:https://www.cnblogs.com/xlhblogs/p/2168653.html