红叶何时落水
首先明白原型链是啥
关键语句:儿子原型的__proto__属性指向父亲的prototype属性,构造函数的prototype属性的constructor属性指向其本身;
经典美图
需求:Vue中data中的数据发生改变时,set属性可以确保响应式;但是我们只是在最开始的时候将所有的data数据都重新定义过一次;
当我们使用数组方法 添加数据时,我们该如何保证新添加的数据是响应式的呢。
对象方法调用会沿着原型链向上寻找,一旦找到,就停止。
那么我们可以插入一个节点,让数组优先使用这个节点的数组方法,而不是原生的。
继承关系: arr -> Array.prototype -> Object.prototype -> ...
继承关系: arr -> 改写的方法 -> Array.prototype -> Object.prototype -> ...
let Method = [
'push',
'pop',
'shift',
'unshift',
'reverse',
'sort',
'splice',
];
let arr = [];
let array_methods = Object.create(Array.prototype);
Method.forEach(method => {
array_methods[method] = function () {
// 将数据进行响应化处理,设置set属性,reactify()看响应式原理那里
// arguments里储存的应该是地址,这里是将该地址的数据属性重写了一下
for (let i = 0; i < arguments.length; i++) {
reactify(arguments[i]);
}
// 确保数组方法可以正常使用
return Array.prototype[method].apply(this, arguments);
}
});
arr.__proto__ = array_methods;
console.log(arr)
这样的话,我们就只是改变了arr他自己的数组方法。
关于原型,还有类的创建
第一种类
利用inherit()
function range(from, to) {
//使用inherit()函数来创建对象,这个对象继承自在下面定义的原型对象
//原型对象作为函数的一个属性存储,并定义所有"范围对象"所共享的方法(行为)
var r = inherit(range.methods);//存储新的"范围对象"的起始位置和结束位置(状态)
//这两个属性是不可继承的,每个对象都拥有唯一的属性
r.from = from;
r.to = to;//返回这个新创建的对象
return r;
}
range.methods = {
method1: function () {
console.log(this);//指向调用它的对象
}
}
let p = range(1, 3);
p.method1();
第二种类
利用new 与 prototype
function Ran(a, b) {
this.a = a;
this.b = b;
}
Ran.prototype = {
method: function() {
console.log(this);
}
}
let s = new Ran(1, 2);
s.method();
第三种类
class Rectangle {
// constructor
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter
get area() {
return this.calcArea()
}
// Method
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
console.log(square.area);
呃,constructor就相当于构造函数;
还有prototype里的constructor指向函数本身,是个无限循环;
前两种类好像没有这个循环,补救一下
fn.prototype={
constructor:fn//显式设置构造函数反向引用
};
犀牛书言:是不是一类取决于原型是不是一致,与构造函数无关;但类名是构造函数的名字;
instanceof运算符并不会检查r是否是由Range()构造函数初始化而来,而会检查r是否继承自Range.prototype。