/** 传统构造函数 */
(function() {
// 1. 设置一个构造函数
function Animal(type, name) {
this.type = type;
this.name = name;
}
// 2. 在 Animal 构造函数的原型对象上 添加一个 getAnimalName 的方法
Animal.prototype.getAnimalName = function() {
return this.name
}
// 3. new 出 cat dog 这样的实例;可以发现, 每个实例上均有 getAnimalName 方法;
const cat = new Animal('cat', '小花');
// console.log(cat.getAnimalName())
const dog = new Animal('dog', '大黄');
// console.log(dog.getAnimalName())
// 4. cat 实例上虽然没有 constructor 属性,但是 cat.__proto__ 上有 constructor 属性,且指向 Animal; 根据原型链的查找规则,实例没有的方法,会沿着 __proto__ 查询;
// console.log(cat.constructor === Animal) // true
})();
/** ES6 class: 不存在变量提升 */
(function() {
class Animal {
// 这里的 constructor === function Animal(type, name) {}; 也就是说 constructor 方法内部的逻辑,就是构造函数内部的代码逻辑
constructor(type, name) {
this.type = type
this.name = name
}
/**
* 在 class 内部直接定义的方法;也就是 写在 原型对象 prototype 中的
* Animal.prototype = { getAnimalName, getAnimalType }
*/
getAnimalName() {
return this.name
}
getAnimalType() {
return this.type
}
/**
* 静态方式:直接定义在 Animal 上面的方式,只能通过 Animal.propName 的方法调用,实例上不可调用
* 通过关键字 static 来实现
*/
static classmethod() {
return 'class'
}
// 资料上说这种方式也不生效的,但是测试发现,有效果
static env1 = 'env1'
// 这种方法设置的不是静态属性,而是动态属性,也就是说是设置在 prototype 上的,实例可以调用
env2 = 'env2'
}
/**
* 静态方式: 目前只能通过下面这种方法;
*/
Animal.environment = 'forest'
const dog = new Animal('dog', '大黄');
// console.log(Animal.classmethod()) // class
// console.log(Animal.env1) // env1
// console.log(Animal.env2) // undefined
// console.log(Animal.environment) // forest
// console.log(dog.classmethod()) // dog.classmethod is not a function
console.log(dog.env1) // undefined
console.log(dog.env2) // env2
console.log(dog.environment) // undefined
console.log(dog.getAnimalName()) // 大黄
})();
ES6 class 理解
最新推荐文章于 2024-09-14 18:52:56 发布