JavaScript中原型与继承(简单例子)
利用原型prototype创建自定义对象Person:
function Person(name,sex){ this.name = name; this.sex = sex; } Person.prototype = { getName:function(){return this.name}, getSex:function(){return this.sex} } var liu = new Person("lcy","female"); //创建一个空白对象 //拷贝Person.prototype中的属性到空对象中(内部实现为一个隐藏的链接) //将这个对象通过this关键字传递到构造函数中并执行构造函数 //将这个对象赋值给对象liu console.log(liu.getName());//lcy Person.prototype.age = 22; console.log(liu.age);//22 liu.age = 24; console.log(liu.age);//24 delete liu.age; console.log(liu.age);//22
创建一个员工类Employee,并且让它继承Person中的name,sex属性已经get方法:
function Employee(name,sex,employeeID){ this.name=name; this.sex=sex; this.employeeID=employeeID; } //将Employee的原型指向Person的一个实例 Employee.prototype=new Person();
Employee.prototype.constructor=Employee; Employee.prototype.getEmployeeId=function(){return this.employeeID;}; var chen=new Employee("chen","female",001); console.log(chen.getName());