- 有如下代碼,解釋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("若愚")
p.sayName();
當(dāng)new一個(gè)構(gòu)造函數(shù)的時(shí)候會(huì)創(chuàng)建一個(gè)對象寇漫,p為通過new Person創(chuàng)建的對象刊殉,構(gòu)造函數(shù)Person.prototype等于被創(chuàng)建的對象p的
__proto__
殉摔。構(gòu)造函數(shù)Person下的Person.prototype內(nèi)的constructor指向此構(gòu)造函數(shù)Person本身。
-
上例中记焊,對對象 p可以這樣調(diào)用 p.toString()逸月。toString是哪里來的? 畫出原型圖?并解釋什么是原型鏈。
圖中可知遍膜,
p.__proto__ === People.prototype
, 在對象p中沒有的方法將會(huì)在p.__proto__
也就是People.prototype
下尋找;People.prototype.__proto__ === Object.prototype
彻采,如果在People
的內(nèi)部對象People.prototype
中沒有的方法將會(huì)在People.prototype.__proto__
也就是Object.prototype
中尋找,最終toString
方法在Object.prototype
中找到捌归,被對象p調(diào)用肛响。原型鏈:Javascript的原型鏈?zhǔn)莾?nèi)部對象鏈:每個(gè)被創(chuàng)建的函數(shù)都有一個(gè)
__proto__
, 都指向創(chuàng)建這個(gè)函數(shù)的'父函數(shù)'的內(nèi)部對象xxx.prototype
。Object.prototype.__proto__
為最終點(diǎn)惜索,指向null特笋。對String做擴(kuò)展,實(shí)現(xiàn)如下方式獲取字符串中頻率最高的字符
//todo....
var str = 'ahbbccdeddddfg';
var ch = str.getMostOften();
console.log(ch); //d , 因?yàn)閐 出現(xiàn)了5次
//todo....
String.prototype.getMostOften = function(){
var str = this,
dict = {},
num = 0,
keyMax;
for(var i = 0; i < str.length; i ++){
if (dict[str[i]] === undefined) {
dict[str[i]] = 1;
} else {
dict[str[i]] ++;
}
}
for(var key in dict){
if(dict[key] > num){
num = dict[key];
keyMax = key;
}
}
return keyMax + ':' + num;
}
var str = 'ahbbccdeddddfg';
var ch = str.getMostOften();
console.log(ch); //d , 因?yàn)閐 出現(xiàn)了5次
- instanceOf有什么作用巾兆?內(nèi)部邏輯是如何實(shí)現(xiàn)的猎物?
- instanceof運(yùn)算符返回一個(gè)布爾值,表示指定對象是否為某個(gè)構(gòu)造函數(shù)的實(shí)例角塑。
var x = [a,b,c];
var y = {};
x instanceof Array // true
y instanceof Object // true
- 它的運(yùn)算實(shí)質(zhì)是檢查右邊構(gòu)建函數(shù)的原型對象蔫磨,是否在左邊對象的原型鏈上。
p instanceof People// 等同于
People.prototype.isPrototypeOf(p)
- 內(nèi)部原理:
function isObjInstanceOffunc(obj,func) {
var __proto__=obj.__proto__;
do{
if(__proto__===func.prototype) return true;
}while(__proto__=__proto__.proto__)
return false;
}
本博客版權(quán)歸 本人和饑人谷所有圃伶,轉(zhuǎn)載需說明來源