首页 > 语言 > JavaScript > 正文

js中继承的几种用法总结(apply,call,prototype)

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

一,js中对象继承

js中有三种继承方式

1.js原型(prototype)实现继承
代码如下:
<SPAN style="BACKGROUND-COLOR: #ffffff"><SPAN style="FONT-SIZE: 18px"><html> 
<body> 
<script type="text/javascript"> 
    function Person(name,age){ 
        this.name=name; 
        this.age=age; 
    } 
    Person.prototype.sayHello=function(){ 
        alert("使用原型得到Name:"+this.name); 
    } 
    var per=new Person("马小倩",21); 
    per.sayHello(); //输出:使用原型得到Name:马小倩 

     
    function Student(){} 
    Student.prototype=new Person("洪如彤",21); 
    var stu=new Student(); 
    Student.prototype.grade=5; 
    Student.prototype.intr=function(){ 
        alert(this.grade); 
    } 
    stu.sayHello();//输出:使用原型得到Name:洪如彤 
    stu.intr();//输出:5 
</script> 
</body> 
</html></SPAN></SPAN> 

2.构造函数实现继承
代码如下:
<SPAN style="FONT-SIZE: 18px"><html> 
<body> 
<script type="text/javascript"> 
    function  Parent(name){ 
        this.name=name; 
        this.sayParent=function(){ 
            alert("Parent:"+this.name); 
        } 
    } 

    function  Child(name,age){ 
        this.tempMethod=Parent; 
        this.tempMethod(name); 
        this.age=age; 
        this.sayChild=function(){ 
            alert("Child:"+this.name+"age:"+this.age); 
        } 
    } 

    var parent=new Parent("江剑臣"); 
    parent.sayParent(); //输出:“Parent:江剑臣” 
    var child=new Child("李鸣",24); //输出:“Child:李鸣 age:24” 
    child.sayChild(); 
</script> 
</body> 
</html></SPAN>

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

图片精选