private variables:原始的定义变量的方法 var
private functions:通过 var functionName=function(){}声明
privileged methods: 通过this.methodName=function(){}声明
privileged properties:通过 this.variableName来声明
(有些地方把privileged properties叫做public properties,但我感觉无论是按照
定义写法,还是为了便于理解都叫privileged properties更好些。更便于对比对称记忆)
prototype methods :通过Classname.prototype.methodname=function(){}来声明
(有些地方叫public method,同样和上边一样的理由,这里改叫prototype method)
prototype properties:通过 classname.prototype.propertyName=somevalue来声明
static properties: 通过classname.propertyName=somevalue定义
static method :通过classnamne.methodName来声明
说明:有些地方(例如我看的文档中)把privileged properties和prototype method叫成
public properties 和public method,不知道为什么这样叫。这样命名后造成的问题是
1,privileged method没有对应的privileged properties
2,prototype properties没有对应的prototype method
3,public method和public properties的定义方式又不对称
下边解释一下几种情况:
1,private:定义在类内部,只能被类内部的方法调用,例如privileged(见实例一中的(1)(2))
2,priviledged :定义在类内部,能被任何调用,在调用上有点类似Java中
的非静态public方法(见实例一中的(3))
3,prototype:这个概念不太好理解,在执行上有点像java的clone,只在类初始化的时候
执行一次。每次建立实例的时候不执行。能被继承。
4,static: 有点类似java中的静态。各实例共享,不能被继承
实例一如下:
<script>
function Pet(name,color)
{
//priviledged properties
this.name=name;
this.color=color;
//private properties
var type="animal";
//private method
var run2 = function()
{
run(type);
}
var run = function(mType)
{
alert(color+" "+name+" is runing("+mType+")");
}
//priviledged method
this.callRun = function()
{
/**//*(1)priviledged method can visit private properties and private method*/
run(type);
}
}

Pet.prototype.callPrivateRun =function(pet)
{
/**//*(2)can not call run*/
//pet.run2();
/**//*(3)can call priviledge method and priviledge properties*/
pet.callRun();
}

function test()
{
var pet = new Pet("pig","black");
pet.callRun();
alert("prototype");
pet.callPrivateRun(pet);
}
window.onload=test;
</script>实例二演示了继承、覆写
另外javascript不支持多态性
<script>
function Pet()
{
//name
this.name=null;
this.getName = function()
{return this.name;};
this.setName = function(newName)
{this.name = newName;};
//abstract method
this.eat = null;
}
/**//*cat inherit from Pet*/
Cat.prototype = new Pet();
function Cat()
{
//implement the abstract method
this.eat = function(food)
{
alert("The cat (" + this.name+ ") is eating " + food);
}
}
/**//*dog inherit from Pet*/
function Dog()
{
//implements the abstract method
this.eat = function(food)
{
alert("The dog (" + this.name+ ") is eating " + food);
}
}
Dog.prototype = new Pet();
/**//*Hound inherit from dog*/
Hound.prototype = new Dog()
function Hound()
{
//override
this.eat = function(food)
{
alert("The Hound (" + this.name+ ") is eating " + food);
}
}

function test()
{
var cat = new Cat();
cat.setName("mimi");
cat.eat("fish");
var dog = new Dog();
dog.setName("wangwang");
dog.eat("bone");
var hound = new Hound();
hound.setName("hali");
hound.eat("rabbit");
}
window.onload=test;
</script>
1343

被折叠的 条评论
为什么被折叠?



