没有合适的资源?快使用搜索试试~ 我知道了~
注:本章中的jClass的实现参考了Simple JavaScript Inheritance的做法。 首先让我们来回顾一下第一章中介绍的例子: function Person(name) { this.name = name; } Person.prototype = { getName: function() { return this.name; } } function Employee(name, employeeID) { this.name = name; this.employeeID = employeeID; } Employee.prototype = new Pers
资源详情
资源评论
资源推荐
JavaScript 继承详解(三)继承详解(三)
注:本章中的jClass的实现参考了Simple JavaScript Inheritance的做法。
首先让我们来回顾一下第一章中介绍的例子:
function Person(name) {
this.name = name;
}
Person.prototype = {
getName: function() {
return this.name;
}
}
function Employee(name, employeeID) {
this.name = name;
this.employeeID = employeeID;
}
Employee.prototype = new Person();
Employee.prototype.getEmployeeID = function() {
return this.employeeID;
};
var zhang = new Employee(“ZhangSan”, “1234”);
console.log(zhang.getName()); // “ZhangSan”
修正constructor的指向错误
从上一篇文章中关于constructor的描述,我们知道Employee实例的constructor会有一个指向错误,如下所示:
var zhang = new Employee(“ZhangSan”, “1234”);
console.log(zhang.constructor === Employee); // false
console.log(zhang.constructor === Object); // true
我们需要简单的修正:
function Employee(name, employeeID) {
this.name = name;
this.employeeID = employeeID;
}
Employee.prototype = new Person();
Employee.prototype.constructor = Employee;
Employee.prototype.getEmployeeID = function() {
return this.employeeID;
};
var zhang = new Employee(“ZhangSan”, “1234”);
console.log(zhang.constructor === Employee); // true
console.log(zhang.constructor === Object); // false
创建Employee类时实例化Person是不合适的
但另一方面,我们又必须依赖于这种机制来实现继承。 解决办法是不在构造函数中初始化数据,而是提供一个原型方法(比
如init)来初始化数据。
// 空的构造函数
function Person() {
}
Person.prototype = {
init: function(name) {
this.name = name;
},
getName: function() {
return this.name;
}
}
// 空的构造函数
function Employee() {
}
// 创建类的阶段不会初始化父类的数据,因为Person是一个空的构造函数
Employee.prototype = new Person();
Employee.prototype.constructor = Employee;
Employee.prototype.init = function(name, employeeID) {
this.name = name;
this.employeeID = employeeID;
};
Employee.prototype.getEmployeeID = function() {
return this.employeeID;
};
这种方式下,必须在实例化一个对象后手工调用init函数,如下:
var zhang = new Employee();
zhang.init(“ZhangSan”, “1234”);
console.log(zhang.getName()); // “ZhangSan”
如何自动调用init函数?
剩余12页未读,继续阅读
weixin_38676851
- 粉丝: 8
- 资源: 895
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论0