首页 > 语言 > JavaScript > 正文

javascript关于继承的用法汇总

2024-05-06 14:48:54
字体:
来源:转载
供稿:网友

本文实例汇总了javascript关于继承的用法。分享给大家供大家参考。具体如下:

例子:
代码如下:/**
* 实现子类继承父类,但不会产生多余的属性和方法
* @returns {Function}
*/
define(function(){
return function(subType, superType){
var proto = new Object(superType.prototype);
proto.constructor = subType;
subType.prototype = proto;
};
});
//——————————————————————————
define(function(){
function ostring(s)
{
this.str = s;
this.length = this.str.length;
}
ostring.prototype.show = function(){
alert(this.str);
};
return ostring;
});
//——————————————————————————
define(['inherit', 'ostring'], function(inherit, ostring){
function wstring(s){
//用call实现调用父类构造函数
ostring.call(this, s);
this.chlength = 2 * s.length;
}
//继承其他的属性
inherit(wstring, ostring);
wstring.prototype.add = function(w)
{
alert(this.str + w);
};
return wstring;
});

再看例子
一、用function实现:
代码如下:function Person(name) {
    this.name = name;
}
Person.prototype.getName = function() {
    return this.name;
}
function Author(name, books) {
    this.inherit=person;
    this.inherit(name);
    this.books = books;
   
}
var au=new Author("dororo","Learn much");
au.name
或者同等效力的:
代码如下:function Person(name) {
    this.name = name;
}
Person.prototype.getName = function() {
    return this.name;
}
function Author(name, books) {
    Person.call(this, name);
    this.books = books;
   
}
var au=new Author("dororo","Learn much");
au.getName
由于这只是将this作为参数,调用父类Person的构造函数,把赋予父类的所有域赋予Author子类,所以任何父类Person构造函数之外的定义的域(原型prototype),子类都不会继承。所以上面例子中,au.getName将是没有被定义的(undefined),因为getName是在Person的原型对象中定义的。

而且,子类的构造函数要在定义自己的域之前调用父类构造函数,免得子类的定义被父类覆盖掉。也就是说,Author定义属性book要在Person.call之后,否则会被Person中属性覆盖。同时,在子类中也最好不要用prototype来定义子类的函数域,因为在一个子类被new,实例化之后就要执行prototype,然后才是调用父类的构造函数,这样也容易被父类的属性覆盖掉。

二、用prototype实现:

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选