Javascript面向对象编程——对象继承的写法
2010-09-25 11:12
323 查看
对象,具有属性与方法。这是大家都听到烂的话了。面向对象的基本特征有:封闭、继承、多态。今天来我总结一下我刚刚学到的,我只是把看到的冰山一角写下来了,希望可以完善。
对象的继承相信大家都很熟悉了。可以用对象冒充、call()[apply()]、原型方式、混合方式这几种。其中混合方式我觉得是比较好的,先开回顾一下call()方法:
几个例子,都可以去试一下。我从来没想过高手会看这些文章,只是写之前刚入门的。所以要是写的不好就不要见怪了。这些Demo只要试过了,加上你查的资料应该对这个JavaScript继承这一块就熟悉了。值得说的是,有很多的写法,我们新手是没见过的。像混合方式的另一种写法,我是不经常这样用。在我看来就是一个数组,这样理解会好很多。例子看多了,看难的例子就不会晕。不过我看到长的还是会晕,还会出现_string_这种,虽然没什么了不起,看得心里不明白就不想看下去了。所以,要学真功夫还是没这么简单的。
还忘了一点,在写call()的时候,我一开始是这样写的:xxx.call(this,a,b);但是这样却报错了。为什么呢?这里要谢谢JS群里的司马闲大哥,call(thisobj,args[0]…)。如果像我那样写,不仅是参数不对,还有就是根本乱用参数。
对象的继承相信大家都很熟悉了。可以用对象冒充、call()[apply()]、原型方式、混合方式这几种。其中混合方式我觉得是比较好的,先开回顾一下call()方法:
原型方式:function car(price){ this.price=price; } car.prototype={ sayPrice:function(){console.log("Price is "+this.price);} //console.log()参见Firebug API } function toyCar(price){ this.price=price; } toyCar.prototype=new car() var oCar=new car("100W"); oCar.sayPrice(); var oCar2=new toyCar("10CNY"); oCar2.sayPrice();
混合方式:混合方式另一种写法: function house(size,price){ this.size = size; this.price = price; } house.prototype={ showArea:function(){ console.log("面积为"+this.size); }, sayPrice:function(){ console.log("价钱为"+this.price); } } function maofan(size,price){ house.call(this,size,price); } maofan.prototype=new house(); var newmaofan=new maofan("20 Square meters ","1000CNY"); newmaofan.showArea(); newmaofan.sayPrice();
为继承的对象追加一个方法试试:
function house(size,price){
this.size = size;
this.price = price;
}
house.prototype={
showArea:function(){
console.log("面积为"+this.size);
}, sayPrice:function(){
console.log("价钱为"+this.price);
}
}
function maofan(size,price){
house.call(this,size,price);
}
maofan.prototype=new house();
maofan.prototype.Sayid=function(id){ //在继承了之后再添加方法,不然就出错了,找不到方法
this.id = id;
console.log("ID is:"+this.id);
}
var newmaofan=new maofan();
newmaofan.Sayid("888");//Output ID:888
几个例子,都可以去试一下。我从来没想过高手会看这些文章,只是写之前刚入门的。所以要是写的不好就不要见怪了。这些Demo只要试过了,加上你查的资料应该对这个JavaScript继承这一块就熟悉了。值得说的是,有很多的写法,我们新手是没见过的。像混合方式的另一种写法,我是不经常这样用。在我看来就是一个数组,这样理解会好很多。例子看多了,看难的例子就不会晕。不过我看到长的还是会晕,还会出现_string_这种,虽然没什么了不起,看得心里不明白就不想看下去了。所以,要学真功夫还是没这么简单的。
还忘了一点,在写call()的时候,我一开始是这样写的:xxx.call(this,a,b);但是这样却报错了。为什么呢?这里要谢谢JS群里的司马闲大哥,call(thisobj,args[0]…)。如果像我那样写,不仅是参数不对,还有就是根本乱用参数。
相关文章推荐
- [转]Javascript面向对象编程(三):非函数对象的继承
- Javascript面向对象编程(三):非函数对象的继承
- Javascript面向对象编程(三):非函数对象的继承
- JavaScript面向对象编程(10)快速构建继承关系之对象拷贝
- JavaScript面向对象编程(10)高速构建继承关系之对象拷贝
- javascript面向对象编程的学习---对象继承
- javascript面向对象编程的学习---对象继承
- Javascript对象继承
- C++ 知识点(三):面向对象编程:类,对象,继承,重载
- 【Javascript学习笔记】由JavaScript中call()方法引发的对面向对象继承机制call的思考
- 由JavaScript中call()方法引发的对面向对象继承机制call的思考
- javascript的函数、创建对象、封装、属性和方法、继承
- javascript 特殊的面向对象以及继承详解(入门篇)
- javascript继承对象
- 韩顺平_轻松搞定网页设计(html+css+javascript)_第29讲_二维数组转置_js面向对象编程介绍 类(原型对象)和对象_学习笔记_源代码图解_PPT文档整理
- JavaScript 面向对象思想以及原型、继承
- javascript_core_09之继承、属性、对象
- 【自】JavaScript面向对象初探二:通过编写一个拖拽例子,让我们了解对象的继承
- JavaScript 的继承机制----对象冒充
- javascript 面向对象基础(四)面向对象的继承