`
liebaorun
  • 浏览: 22319 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

JavaScript Prototype继承实践

阅读更多
JavaScript为基于对象及Prototye的语言,个人觉得其Prototype继承要注意的两个方面:
1.子类可以通过prototype链访问父类的方法与属性
2.子类构造函数调用的构造函数,初始化父类属性

function Person(id1, name1){
this.id = id1;
this.name = name1;

};

Person.prototype.getInfo = function(){
alert(this.id + ":" + this.name);
};

function Employee(id, name, salary){
this.salary = salary;
        //调用父类构造函数 
Person.prototype.constructor.call(this,id,name);
};

//构造Prototype链
Employee.extend = function(Person){
function Temp(){};
Temp.prototype = Person.prototype;
Employee.prototype = new Temp();
        //复原Employee构造函数
Employee.prototype.constructor = Employee;
};


Employee.extend(Person);

Employee.prototype.getSalary = function(){
alert(this.salary);
};

Employee.prototype.getInfo = function(){
alert(this.id + ":" + this.name+":"+this.salary);
};

var employee = new Employee("1","ep1",8000);

employee.getInfo();
employee.getSalary();

new Person("2","person2").getInfo();

备注:JavaScript中没有类的概念,上面提到的类实际上都是函数,一般情况下,函数通过new关键字调用后,返回一个对象,它可以看作是此函数的实例,所以我们便称此函数为类,返回的对象为类的实例.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics