javascript对象构建、继承

//构造函数添加属性
function Person(name,age,sex){
    this.name=name;
    this.age=age;
    this.sex=sex;
    this.common="公用";
}
//原型添加方法
Person.prototype={
    constructor:Person,//用字变量
    talk:function(){
        alert(this.name+"说话");
    }, 
    high:188,//原型的属性具有共享性:基本属性共享内容,引用属性共享引用指针
    friends:['a','b']
}

//通过构造函数继承属性
function Man(name,age,profession){
    Person.call(this,name,age,'男');
    this.profession=profession;
}

Man.prototype=new Person();//继承原型里的属性和方法

//扩展方法(不能用字变量形式)
Man.prototype.say=function(){
 alert('say'+this.profession);
}


function test(){
    var m= new Man('zhf',22,'学生');
    console.log(m);
    m.talk();
    m.say();
}



//测试js对象构建
function main(){
     var p = new Person('张三',11,'男');
     var p2 = new Person('王五',11,'男');
    p.talk();
    p2.talk();

    alert(p.constructor);

    p.common="私用";
    alert(p.common);
    alert(p2.common);
    p.high=11;
    alert(p.high);
    alert(p2.high);

    p.friends.push('c');
    alert(p.friends);
    alert(p2.friends);
 }
 
 //main();
test();
原文地址:https://www.cnblogs.com/cxyzl/p/3025572.html