您的位置:首页 > Web前端 > JavaScript

一个关于js中prototype的小实例

2009-09-10 14:19 477 查看
什么是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还有什么好玩的特性呢?……学习研究中……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: