看看new關鍵字干了什么
var p={};
p.__proto__=Person.prototype;
Person.call(p);
然后,看看繼承都干了什么東西咯。
首先是繼承的一般寫法。
function Step1(){
}
Step1.prototype.a=100;
function Step2(){
}
Step2.prototype=new Step1()
Step2.prototype.b=200;
function Step3(){
}
Step3.prototype=new Step2();
let a=new Step3();
這個應該很容易看懂。
結合上面所說的new的過程。
a的 __proto__ 是 Step3的prototype ,Step3的prototype則是Step2的實例。Step2的實例的__proto__ 則是Step2的 prototype,Step2的protype是Step1的實例并且加上了一個b屬性,而Step1的實例的__proto__則是Step1的prototype。
于是說是這樣的。
a.__proto__=Step3.prototype;
a.__proto__.__proto__=Step2.prototype;
a.__proto__.__proto__.__proto__=Step1.prototype;
這個就是原型鏈了。
說說instanceof 都做了什么
function instance_of(L, R) {//L 表示左表達式,R 表示右表達式
var O = R.prototype;// 取 R 的顯示原型
L = L.__proto__;// 取 L 的隱式原型
while (true) {
if (L === null)
return false; //表示原型鏈到達最后了,Object.__proto__.__proto__===null
if (O === L)// 這里重點:當 O 嚴格等于 L 時,返回 true
return true;
L = L.__proto__;
}
}
說的很明白了,instanceof就是不斷往后看看有沒有原型和右邊一樣的。
function deepCopy(obj){
let copy = {};
if (typeof obj === 'object'){
if(obj instanceof Array){
let lengthOfArray=obj.length;
let copideArray=[];
for(let i=0;i<=lengthOfArray-1;i++){
let item = obj[i];
if(item instanceof Array){
item = deepCopy(item);
}
else if(item instanceof Object){
item = deepCopy(item);
}
copideArray.push(item);
}
copy=copideArray;
}
else if(obj === null){
copy=null;
}
else{
for (each in obj){
let valueOfeach=obj[each];
if (valueOfeach instanceof Array){
let subObj = deepCopy(valueOfeach);
copy[each]=subObj;
}
else if(typeof valueOfeach === 'object'){
let subObj = deepCopy(valueOfeach);
copy[each]=subObj;
}
else{
copy[each]=valueOfeach;
}
}
}
}
else{
copy=obj;
}
return copy;
}
當然,上面的東西也是會出很多問題的比如arraybuffer 和 其他的類似array的對象。
代碼很簡單。但是卻讓我知道了typeof 和 instanceof 的不同之處。