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",
"haoel@hotmail.com",
"http://jb51.net",
"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)
}
return result;
}
Object.getPrototypeOf() 函数
复制代码 代码如下:
function proto(object) {
return !object? null
: '__proto__' in object? object.__proto__
: /* not exposed? */ object.constructor.prototype
}
bind 函数
复制代码 代码如下:
var slice = [].slice
function bind(fn, bound_this) { var bound_args
bound_args = slice.call(arguments, 2)
return function() { var args
args = bound_args.concat(slice.call(arguments))
return fn.apply(bound_this, args) }
}
参考
W3CSchool
MDN (Mozilla Developer Network)
MSDN (Microsoft Software Development Network)
您可能感兴趣的文章: