- ES5 没有类的概念 通过构造函数来实现 constructor() 命名规则:首字母大写
ES6 类的继承
- ES6 通过 class 实现,类的三种属性
- 类的公有属性:可以通过 proto 直接找到公有属性
- 类的私有属性
- 类的静态属性:静态方法
ES5 概念定义
- 原型链存在于任何地方(类 函数 方法 对象 变量等等)
- 原型链空间中的 constructor 属性 指向的是 所属者
function Parent() {
// 构造函数中的 this指向 主要根据调用的方式来决定
// 通过 new 方式来调用 this指向的就是实例
// 通过函数的方式引用 this指向的就是 window
this.name = "parent"; //私有属性
}
// 通过原型链定义公有属性
Parent.prototype.eat = function() {
console.log("eat");
};
console.log(Parent.prototype.constructor === Parent); // true
- 获取构造函数私有属性
function Parent() {
this.name = "parent"; //私有属性
}
let parent = new Parent();
console.log(parent.name);
- 获取构造函数的公有属性
可通过proto 获取,也可以直接获取(先查找私有属性没有继续向上找公有属性查找)
function Parent() {
this.name = "parent"; //私有属性
}
// 公有属性 (可通过__proto__ 获取,也可以直接获取,直接获取是自动向上查找出来)
Parent.prototype.eat = function() {
console.log("eat");
};
let parent = new Parent();
console.log(parent.__proto__.eat()); // eat
console.log(parent.eat()); // eat
实例可以获取自己的构造函数
- 实例可以通过 constructor 获取到自己的构造函数
- 实例 不可以通过 constructor 指向去拿构造函数内定义的属性值
- 构造函数 不可以拿到自己的定义的属性值
function Parent() {
this.name = "parent";
}
Parent.prototype.eat = function() {
console.log("eat");
};
let parent = new Parent();
console.log(parent.__proto__.constructor);
// [Function: Parent]
function Parent() {
this.data = 1;
}
Parent.prototype.eat = function() {
console.log("eat");
};
let parent = new Parent();
console.log(parent.__proto__.constructor.data); // undefined
console.log(Parent.data); // undefined
两个类的继承
- 继承私有属性
- 在儿子类中调用父类
父类名称.call(this);
实现继承
function Parent (){
this.data = 1;
};
function Child(){
this.data1 = 2;
Parent.call(this); //继承Parent类的私有属性
};
let childs = new Child()
console.log(childs.data)
// 1
- 继承公有属性
- 方法一(ES5写法):在实例化子类之前 调用一次
子类名.prototype.__proto__ = 父类名.prototype;
- 方法二(ES6写法):
Object.setPrototypeOf(Child.prototype,Parent.prototype);
- 方法三(ES6写法):
function Parent (){
this.data = 1;
};
Parent.prototype.eat = function(){
console.log('吃饭')
}
function Child(){
this.data1 = 2;
Parent.call(this); //继承父类私有属性
};
Child.prototype.eat1 = function(){
console.log('吃饭1')
}
// 继承父类公有属性 -- ES5写法
// Child.prototype.__proto__ = Parent.prototype;
// 继承父类公有属性 -- ES6
Object.setPrototypeOf(Child.prototype,Parent.prototype);
let childs = new Child();
console.log(childs.data); //1
console.log(childs.eat()); //吃饭
console.log(childs.data1); //2
console.log(childs.eat1()); // 吃饭1
个人博客cometang: www.gotang.cn
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 模板不会安装或需要功能定制以及二次开发?
发表评论
还没有评论,快来抢沙发吧!