为JavaScript所有对象添加一个继承方法
本继承方法仍然是基于JavaScript原型属性来实现的.
Function.prototype.inherit = function(parent){ this.prototype = Object.create(parent.prototype); this.prototype.constructor = this; };
本方法扩展到Function对象上,目的是让JavaScript中所有的构造函数都拥有此方法.
参数说明:
* parent: 被继承的父类构造函数.
用法示例如下:
Function.prototype.inherit = function(parent){ this.prototype = Object.create(parent.prototype); this.prototype.constructor = this; }; function People(name,age){ this.name = name; this.age = age; } People.prototype = { getName:function(){ return this.name; }, say:function(){ console.log("hello"); } }; function Student(name,age,id){ People.call(this,name,age); this.id = id; } Student.inherit(People); Student.prototype.getId = function(){ return "this id is " + this.id; }; var s = new Student("Jhon",22,3.1415926); console.log(s.getName()); console.log(s.say()); console.log(s.getId()); console.log(s.constructor);
相关推荐
nmgxzm00 2020-11-10
ifconfig 2020-10-14
hhanbj 2020-11-17
zfszhangyuan 2020-11-16
古叶峰 2020-11-16
一个智障 2020-11-15
jipengx 2020-11-12
81427005 2020-11-11
xixixi 2020-11-11
游走的豚鼠君 2020-11-10
苗疆三刀的随手记 2020-11-10
Web卓不凡 2020-11-03
小飞侠V 2020-11-02
帕尼尼 2020-10-30
爱读书的旅行者 2020-10-26
帕尼尼 2020-10-23
杏仁技术站 2020-10-23
淼寒儿 2020-10-22