现在的位置: 首页 > 综合 > 正文

一个关于js中prototype的小实例

2012年11月05日 ⁄ 综合 ⁄ 共 697字 ⁄ 字号 评论关闭

什么是prototype呢?看书,GOOGLE之,还问了一只很特别的鸟,学到了一点点,如下面的小实例:

 

<html>
<body>

<script lang="text/javascript">
function father(){
    
this.plus_other = function(){
        alert(
'plus_other: ' + this.cityId);
    }

}
function City(){
    
this.plus_other = function(){
        alert(
'plus_other!');
    }
}
function City2(){}

City.prototype = father;
City2.prototype 
= father;

City.prototype.plus = function(){
    alert(
'plus!');
}

var city1 = new City();
city1.plus_other();

var city2 = new City2();
//city2.plus_other(); 没有这个方法,所以这行会报错
city.plus();

</script>
</body>
</html>

 

其实prototype(原型)就是类似于基类……,而使用 “某对象A.prototype.XXX” 的方法就是把新的方法或者属性定义到 “A对象”的原型(类似于父类、基类)中去。所以city2对象也有plus方法,但是city2对象没有plus_other方法。

prototype还有什么好玩的特性呢?……学习研究中……

 

 

抱歉!评论已关闭.