用es5没有class,可以通过function构造函数去模拟class
function define(target, properties) {
if (!Array.isArray(properties)) return;
properties.forEach(property => {
Object.defineProperty(target, property.key, {
configurable: true,
enumerable: false,
value: property.value
})
});
}
function createClass(Constructor, protoProperties, staticProperties) {
define(Constructor.prototype, protoProperties);
define(Constructor, staticProperties);
}
const Animal = (function() {
function Animal() {
this.name = "老虎";
}
createClass(
Animal, [{
key: 'bark',
value: () => {
console.log('动物都会吃')
}
}], [{
key: 'parent',
value: 'Parent'
}])
return Animal;
})();
let animal = new Animal();
console.log(animal.name);
animal.bark();
console.log(Animal.parent);
继承
- Parent.call(this) 2.
- 原型重定向
- 静态重定向
function Tiger() {
Animal.call(this);
}
function create(parentPrototype) {
function Fn() {}
Fn.prototype = parentPrototype;
return new Fn();
}
Tiger.prototype = Object.create(Animal.prototype, { constructor: { value: Tiger } });
let tiger = new Tiger();
console.log(tiger);
console.log(tiger.name);
console.log(Tiger.prototype.consstructor);
tiger.bark();
原型链
console.log(animal.__proto__ === Animal.prototype);
console.log(animal.__proto__.__proto__ === Object.prototype);
console.log(Object.prototype.__proto__);
console.log(Function.prototype.__proto__ === Object.prototype);
console.log(Function.__proto__ === Object.__proto__);
console.log(Animal.prototype.constructor === Animal);