这样,我们可以通过这一特性来实现继承。还记得我们最最前面的那个Person吧, 下面的示例是创建一个Student来继承Person。
function Person(name, email, website){
this.name = name;
this.email = email;
this.website = website;
};
Person.prototype.sayHello = function(){
var hello = "Hello, I am "+ this.name + ", <br>" +
"my email is: " + this.email + ", <br>" +
"my website is: " + this.website;
return hello;
};
function Student(name, email, website, no, dept){
var proto = Object.getPrototypeOf;
proto(Student.prototype).constructor.call(this, name, email, website);
this.no = no;
this.dept = dept;
}
// 继承prototype
Student.prototype = Object.create(Person.prototype);
//重置构造函数
Student.prototype.constructor = Student;
//重载sayHello()
Student.prototype.sayHello = function(){
var proto = Object.getPrototypeOf;
var hello = proto(Student.prototype).sayHello.call(this) + '<br>';
hello += "my student no is: " + this. no + ", <br>" +
"my departent is: " + this. dept;
return hello;
};
var me = new Student(
"Chen Hao",
"",
"",
"12345678",
"Computer Science"
);
document.write(me.sayHello());
兼容性
上面的这些代码并不一定能在所有的浏览器下都能运行,因为上面这些代码遵循 ECMAScript 5 的规范,关于ECMAScript 5 的浏览器兼容列表,你可以看这里“ES5浏览器兼容表”。
本文中的所有代码都在Chrome最新版中测试过了。
下面是一些函数,可以用在不兼容ES5的浏览器中:
Object.create()函数
function clone(proto) {
function Dummy() { }
Dummy.prototype = proto;
Dummy.prototype.constructor = Dummy;
return new Dummy(); //等价于Object.create(Person);
}
var me = clone(Person);
defineProperty()函数
function defineProperty(target, key, descriptor) {
if (descriptor.value){
target[key] = descriptor.value;
}else {
descriptor.get && target.__defineGetter__(key, descriptor.get);
descriptor.set && target.__defineSetter__(key, descriptor.set);
}
return target
}
keys()函数
function keys(object) { var result, key
result = [];
for (key in object){
if (object.hasOwnProperty(key)) result.push(key)