問答:
1.有如下代碼,解釋Person
, prototype
, __proto__
,p
,constructor
之間的關聯。
function Person(name){
this.name = name;
}
Person.prototype.sayName = function(){
console.log('My name is :' + this.name);
}
var p = new Person("若愚")
p.sayName();
-
Person
是一個構造函數,函數也是對象,那么Person
就擁有屬性prototype
和__proto__
。prototype
指向Person
的原型對象,即Person.prototype
,而__proto__
指向構造Person
的函數的原型,即Function.prototype
。 -
Person.prototype
是Person
的原型對象,擁有屬性constructor
和__proto__
。constructor
指向Person
,__proto__
指向Object.prototype
。 -
p
作為Person
構造出來的實例對象,擁有屬性__proto__
,指向Person.prototype
。
2.上列中,對對象p可以調用p.toString
。toString
是哪里來的?畫出原型圖?并解釋什么是原型鏈。
toString
來自于Object.toString
。原型圖如下:
原型鏈.jpg
當訪問
p.toString
時,先在對象p
的基本屬性中查找,發現沒有,然后通過__proto__
去Person.prototype
中查找,還是沒有,再通過__proto__
去Object.prototype
中查找,最終找到了toString
,完成訪問。當訪問一個對象的屬性或方法時,先在基本屬性中查找,如果沒有,再沿著
__proto__
這條鏈向上找,這就是原型鏈。
3.對String
做擴展,實現如下方式獲取字符串中頻率最高的字符
String.prototype.getMostOften = function(){
var str = this;
var obj = {}; //創建一個obj對象用來儲存每個字符元素和它出現的次數
for (var i = 0;i<str.length;i++){
if(!obj[str[i]]){ //判斷當前字符是否在obj對象中出現過
obj[str[i]] = 1; //如果沒有出現過,次數為1
}else{
obj[str[i]] ++; //如果出現過,次數加1
}
}
console.log(obj);
var max = 0; //初始化一個最大次數
var mostWord= []; //創建一個mostWord數組儲存出現最多的字符
for(var key in obj){
if(obj[key] > max){
max = obj[key];
mostWord = []; //找到出現次數最多的字符后,清空數組,將該字符儲存到數組中。
mostWord.push(key);
}
else if( obj[key] === max){
mostWord.push(key) //若有多個字符出現的次數相同,也儲存到數組中。
}
}
var result = mostWord.join("和");
console.log("出現次數最多的字符為:"+result+",出現"+max+"次");
}
運行結果
4.instanceof
有什么作用?內部邏輯是如何實現的?
- 作用:
instanceof
運算符用來檢測某個構造函數的原型是否存在于要檢測的對象的原型鏈上。在判斷引用類型的時候,可以用到該運算符。 - 內部邏輯:
instanceof
運算符的第一個變量是一個對象:obj,第二個對象一般是一個構造函數:Func。判斷邏輯是:沿著obj.__proto__
這條線來找,如果找到一個對象是Func.prototype
,就返回true,如果找到終點都沒有找到,就返回false。用函數表示就是:
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;
}
instanceOf
運算符其實表達就是一個對象的原型鏈結構。結合問答2的原型圖可以看一些有趣的例子:
function Person(name){
this.name = name;
}
Person.prototype.sayName = function(){
console.log('My name is :' + this.name);
}
var p = new Person("若愚")
p.sayName();
console.log(p instanceof Person) //true;
console.log(p instanceof Object) //true;
console.log(Person instanceof Function) //true;
console.log(p instanceof Function) //false;
console.log(Function instanceof Function)//true;
console.log(Function instanceof Object) //true;
console.log(Object instanceof Function) //true;
instanceof
本文版權歸本人和饑人谷所有,轉載請注明來源。