Javascript 类/声明/继承/多态实例

本文介绍了使用JavaScript实现类的继承与多态的方法,通过具体的示例代码展示了如何利用prototype对象进行类的定义与继承。
//声明Person类
var Person = function(name) {  
    this.name = name;
}   
Person.prototype = { // protype与prototype.js并没有关系,只是个名称表示类的原始
     sayHello: function() {  
         alert("hi, javaeye, I'm A " + this.name);  
    }
}   

Object.extend = function(destination, source) {  
for (var property in source) {  
     destination[property] = source[property];  
}  
return destination;  
}
//声明Person1类
var Person1=function(name){
     this.name = name;
}
//Person1继承与多态Person,只继承Person.prototype方法
Person1.prototype=Object.extend(
     Person.prototype,
    {
            //
Person1其他方法声明
       }
)

//实例化,构造
var t = new Person1("dd");
t.sayHello();

根据上面理论,我们来应用prototype.js中创建类:
<script type="text/javascript" src="/inc/jscript/prototype.js"></script>
var Person = Class.create();
Person.prototype= {   
    initialize: function(name) {  
        this.name=name;
    },
  
sayHello: function() {  
         alert("hi, javaeye, I'm A " + this.name);  
    }

};

var Person1 = Class.create();
Person1.prototype=Object.extend(Person.prototype, {   
    initialize: function(name) {  
        this.name=name;
    }
   //Person1其他方法声明
});
//实例化,构造
var t = new Person1("dd");
t.sayHello();

//prototype.js中Calss对像代码:
//var Class = {   
// create: function() {   
//    return function() {   
//      this.initialize.apply(this, arguments);   
//    }   
// }   
//}
//Class.create中返回一个initialize对象,调用new时,将会创建一个新对象,并且调用//Person方法,Person方法会委托给"新产生对象
Person1"的 initialize方法
</script>

转载于:https://www.cnblogs.com/jone_linux/archive/2009/09/15/1567173.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值