1.有如下代碼渐排,解釋Person
炬太、 prototype
、__proto__
驯耻、p
亲族、constructor
之間的關(guān)聯(lián)炒考。
function Person(name){
this.name = name;
}
Person.prototype.sayName = function(){
console.log('My name is :' + this.name);
}
var p = new Person("cxx");
p.sayName();
先清楚以下三點(diǎn):
- 1.每個(gè)函數(shù)都有一個(gè)
prototype
屬性,這個(gè)屬性是一個(gè)指針霎迫,指向一個(gè)對(duì)象斋枢,也就是該函數(shù)的原型對(duì)象; - 2.原型對(duì)象和實(shí)例中都有一個(gè)constructor屬性知给,均指向了構(gòu)造函數(shù)本身瓤帚;
Person.prototype.constructor==Person //true
p.constructor==Person //true
- 3.實(shí)例中有一個(gè)
__proto__
屬性,該屬性指向了原型對(duì)象;
p.__proto__==Person.prototype //true
所以涩赢,在這個(gè)例子中戈次,prototype
是Person
的一個(gè)屬性,該屬性指向了Person
的原型對(duì)象筒扒,也即Person.prototype
是Person
的原型對(duì)象怯邪,constructor
是該原型對(duì)象的一個(gè)屬性,指向Person
; p
是Person
的一個(gè)實(shí)例花墩,該實(shí)例擁有__proto__
屬性悬秉,該屬性指向Person.prototype
。
2.上例中冰蘑,對(duì)對(duì)象 p可以這樣調(diào)用 p.toString()和泌。toString是哪里來的? 畫出原型圖?并解釋什么是原型鏈。
當(dāng)訪問
p.toString
時(shí)懂缕,先在對(duì)象p的基本屬性中查找允跑,發(fā)現(xiàn)沒有,然后通過__proto__
去Person.prototype
中查找搪柑,還是沒有聋丝,再通過__proto__
去Object.prototype中
查找,最終找到了toString()方法工碾。當(dāng)訪問一個(gè)對(duì)象的屬性或方法時(shí)弱睦,先在基本屬性中查找,如果沒有渊额,再沿著
__proto__
這條鏈向上找况木,這就是原型鏈。
3.對(duì)String做擴(kuò)展旬迹,實(shí)現(xiàn)如下方式獲取字符串中頻率最高的字符
String.prototype.getMoreOften=function(){
var str=this,
count=0,
letter="";
while(str.length>0){
for(var i=0; i<str.length; i++){
re=new RegExp(str.split("")[0],"g");
if(count<str.match(re).length){
count=str.match(re,"").length;
letter=str.split("")[0];
}
str=str.replace(re,"");
}
}
return letter;
}
4.instanceof有什么作用火惊?內(nèi)部邏輯是如何實(shí)現(xiàn)的?
instanceof 的作用是判斷一個(gè)對(duì)象是不是一個(gè)函數(shù)的實(shí)例奔垦。實(shí)現(xiàn)方式是通過判斷某個(gè)實(shí)例對(duì)象的內(nèi)部指針__proto__
是否與所測(cè)試對(duì)象(函數(shù))的prototype屬性相等來實(shí)現(xiàn)
function instanceof(obj,Func){
var __proto__ = obj.__proto__;
do{
if(__proto__ === Func.prototype) return true;
if(!__proto__) return false;
}while(__proto__ = __proto__.__proto__)
return false;
}