码迷,mamicode.com
首页 > Web开发 > 详细

js继承——扩展Object方式实现继承

时间:2018-06-25 14:59:23      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:扩展   func   type   .sh   code   pre   zhang   class   method   

function Parent(name,sex){
    this.name  = name;
    this.sex = sex;
    this.sayName = function(){
        console.log(this.name+‘ : ‘+this.sex);
    }
}

Object.prototype.method = function(obj){
         for (var attr in obj){
            this[attr] = obj[attr];
        }
}

function Son(age){
    this.age = age;
    this.show = function(){
       console.log(this.name+‘ : ‘+this.sex+‘ : ‘+this.age);
    }      
}

var p1 = new Parent(‘zhangsan‘,‘男‘);
var p2 = new Son(23);
p2.method(p1);

p2.show();

因为给原型链的的顶端添加方法,所以所有的对象都会添加此属性和方法

js继承——扩展Object方式实现继承

标签:扩展   func   type   .sh   code   pre   zhang   class   method   

原文地址:https://www.cnblogs.com/jokes/p/9223837.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!