定义
从设计模式来讲,原型模式是用于创建对象的一种模式,通过克隆创建某个类型的对象。
原型继承的基本规则
- 所有的数据都是对象
const obj1 = new Object();
const obj2 = {};
console.log(Object.getPrototypeOf(obj1) === Object.prototype); //ture
console.log(Object.getPrototypeOf(obj2) === Object.prototype); //ture
- 要得到一个对象,不是通过实例化类,而是找到一个对象作为原型克隆它
const obj = {
name: 'seven',
}
const obj1 = Object.create(obj);
console.log(obj1.name) // seven
- 对象会记住它的原型
const a = new Object();
console.log(a.__proto__ === Object.prototype); // true
- 如果对象无法响应某个请求,它会把这个请求委托给它自己的原型
const obj = {
name: 'seven1',
}
const A = function() {};
A.prototype = obj;
const a = new A();
console.log(a.name); // seven1
new运算过程
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
created() {
function Person(name: string) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name
}
const a = this.objectFactory(Person, 'sedf')
console.log(a.name) // sedf
console.log(a.getName()) // sedf
console.log(Object.getPrototypeOf(a) === Person.prototype) // true
},
methods: {
objectFactory() {
const obj = new Object(), // 初始化一个空对象
Constructor = [].shift.call(arguments); // 获取构造函数
obj.__proto__ = Constructor.prototype; // 将实例的__proto__指向构造函数的原型
const ret = Constructor.apply(obj, arguments); // 执行构造函数,给obj设置属性
return typeof ret === 'object' ? ret : obj; // 确保返回对象
},
}
})
</script>