javascript继承机制
1、构造函数继承
1 2 3 4 5 6 7 8 9 10 11 12 13
| function Animal(){ this.species = "动物"; }
function Cat(name, color){ Animal.apply(this, arguments); this.name = name; this.color = color; }
var cat1 = new Cat("大毛", "黄色");
console.log(cat1.species); // 动物 |
1.1、call与apply的区别
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function Animal(name){ this.name = name; this.showName = function(){ console.log(this.name); } }
function Cat(name){ Animal.call(this, name); // class.call(obj, argument1, argument2, ...) // Animal.apply(this, arguments); // class.apply(obj, arguments) }
var cat = new Cat("黑猫警长");
cat.showName(); |
2、原型继承
1 2 3 4 5 6 7 8 9 10 11 12 13
| function Animal(){ this.species = "动物"; }
function Cat(name, color){ this.name = name; this.color = color; }
Cat.prototype = new Animal();
var cat1 = new Cat("大毛", "黄色"); console.log(cat1.species); // 动物 |
2.1 构造函数中使用原型继承需要用类(函数)名,不能用this
function Cat(name, color){
this.prototype = new Animal(); // 无效
Cat.prototype = new Animal(); // 有效
this.name = name;
this.color = color;
}
2.2 apply不能继承原型属性/方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function Animal(name){ this.name = name; }
// Animal.apply(this, arguments); 不能继承该方法 Animal.prototype.showName = function(){ console.log(this.name); }
function Cat(name){ Animal.apply(this, arguments); }
var cat = new Cat("黑猫警长"); cat.showName(); // TypeError: Object #<Cat> has no method 'showName' |
总结:如果使用class.apply/call继承,只在constructor中实现父类的属性和方法,不使用prototype;如果使用class.prototype = new parent_class()继承,则可以使用prototype定义属性和方法。
建议继续学习:
- 在C++里写一个不能被继承的类 (阅读:6229)
- PHP面向对象编程的三大特性 (阅读:4216)
- 多重继承及虚继承中对象内存的分布 (阅读:3728)
- Linux 系统文件描述符继承带来的危害 (阅读:3340)
- 关于python和C++中子类继承父类数据的问题 (阅读:3178)
- C++ 中的接口继承与实现继承 (阅读:3096)
- Javascript继承机制的设计思想 (阅读:3001)
- JavaScript 函数、作用域和继承 (阅读:2951)
- Javascript继承-原型的陷阱 (阅读:2710)
- 再论Javascript的类继承 (阅读:2701)
扫一扫订阅我的微信号:IT技术博客大学习
- 作者:cmpan 来源: 流水孟春
- 标签: 继承
- 发布时间:2013-08-13 13:04:31
-
[888] WordPress插件开发 -- 在插件使用 -
[136] 解决 nginx 反向代理网页首尾出现神秘字 -
[57] 整理了一份招PHP高级工程师的面试题 -
[54] 如何保证一个程序在单台服务器上只有唯一实例( -
[54] 分享一个JQUERY颜色选择插件 -
[54] 用 Jquery 模拟 select -
[53] Innodb分表太多或者表分区太多,会导致内 -
[53] jQuery性能优化指南 -
[51] 海量小文件存储 -
[51] 全站换域名时利用nginx和javascri
