javascript object oriented 面向对象编程初步

2019-06-03 10:23:09王冬梅



让我们用现实世界中的猫来举个例子.猫的 name 和 color 是猫的属性.meeyow(猫叫)是它的一个方法.重要的是任何不同的猫都可能有不同的 name 和 meeyow 的叫声.为了建立适应这些特征的对象类,我们将使用对象构造器. 
<script language="javascript" type="text/javascript"> 
<!-- 

function cat(name) { 
this.name = name; 
this.talk = function() { 
alert( this.name + " say meeow!" ) 

}  

cat1 = new cat("felix") 
cat1.talk() //alerts "felix says meeow!" 

cat2 = new cat("ginger") 
cat2.talk() //alerts "ginger says meeow!" 

//--> 
</script>

在这里,函数 cat() 是一个对象构造器,它的属性和方法在函数体里用this来定义,用对象构造器定义的对象用 new 来实例化.主意我们如何非常容易的定义多个cat 的实例.每一个都有自己的名字,这就是对象构造器带给我们的灵活性.
构造器建立了对象的蓝图.并不是对象本身.
在原型里增加方法.
在上面我们看到的例子里,对象的方法是在构造器里定义好的了.另外一种实现的途径是通过原型(prototype).xxx
原型是javascript继承的一种形式.我们可以为对象定义好后,再创造一个方法.原来所有对象的实例都将共享.
让我们来扩展最初的 cat 对象.增加一个改名的方法.用 prototype 的方式. 
<script language="javascript" type="text/javascript"> 
<!-- 

cat.prototype.changeName = function(name) { 
this.name = name; 


firstCat = new cat("pursur") 
firstCat.changeName("Bill") 
firstCat.talk() //alerts "Bill says meeow!" 

//--> 
</script>

就象你所看到的.我们仅只用了 关键字 prototype 实现了在对象定义后马上增加了changeName方法.这个方法被所有的实例共享.
用原型(prototype) 重载 javascript 对象
原型 在自定义对象和有选择性的重载对象上都可以工作.比如 Date() 或 String 这可能是无止境的.
子类和超类
在JAVA 和C++里,有关于类层次的外在概念.每一个类能有一个角色.
In Java and C++, there is an explicit concept of the class hierarchy. i.e. Every class can have a super class from which it inherits properties and methods. Any class can be extended, or sub-classed so the resulting subclass can inherit its parent's behavior. As we have seen, javascript supports prototype inheritance instead of class based. It's possible for inheritance to happen other ways, however.