原形链

作者: 饥人谷_saybye | 来源:发表于2017-06-28 02:11 被阅读0次

有如下代码,解释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相当于类,p则为Person的实例,p的__proto__指向Person的prototype,
p.__proto__.constructor指向创造他的构造函数Person
p.__proto__===Person.prototype
p.__proto__.constructor===Person
Person.prototype.__proto__ === Object.prototype
Object.prototype.constructor === Object,
Object.prototype.__proto__ === null

上例中,对对象 p可以这样调用 p.toString()。toString是哪里来的? 画出原型图?并解释什么是原型链。

原形链.png

什么是原型链

JS在创建对象(不论是普通对象还是函数对象)的时候,都有一个叫做proto的内置属性,用于指向创建它的函数对象的原型对象prototype。在访问一个对象属性的时候,如果对象本身没有找到这个属性,就会沿着原型链一层一层的寻找。

对String做扩展,实现如下方式获取字符串中频率最高的字符

var str = 'ahbbccdeddddfg';
var ch = str.getMostOften();
console.log(ch); //d , 因为d 出现了5次
String.prototype.getMostOften=function(){
        var hash={}
        for(var key in this){
          var strValue=this[key]
          if(strValue.length==1){
            if(!hash[strValue]){
              hash[strValue]=0;             
            }
            hash[strValue]++
          }
        }
        console.log(hash)
        var char='';
        var num=0;
        for(var _key in hash){         
          if(hash[_key]>num){            
            num=hash[_key]
            char=_key
          }
        }
        console.log(char)
      }
      var str = 'ahbbccdeddddfg';
      var ch = str.getMostOften();

instanceOf有什么作用?内部逻辑是如何实现的?

instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性。
内部逻辑:
e.g.

var arr=[]
var fn=function(){}

arr instanceOf Array //true
arr.__proto__===Array.prototype //true
//内部逻辑为看实例的 __proto__ 是否为构造函数的 prototype 原型
//是则返回true,不是则false

arr instanceOf Object  //true
arr.__proto__===Object.prototype //false
//内部逻辑为看实例的 __proto__ 是否为构造函数的 prototype 原型,这里返回为false则看下一层
arr.__proto__.__proto__===Object.prototype //true
//返回结果为true

fn instanceof Array //false
//内部逻辑为看实例的 __proto__ 是否为构造函数的 prototype 原型
这里返回结果为false则看下一层
fn.__proto__===Array.prototype //false,返回false,则看下一层
fn.__proto__.__proto__===Array.prototype //false,则返回结果为false

arr instanceOf Object  //true
fn.__proto__===Object.prototype //false
//内部逻辑为看实例的 __proto__ 是否为构造函数的 prototype 原型,这里返回为false则看下一层
fn.__proto__.__proto__===Object.prototype //true
//返回结果为true

相关文章

网友评论

      本文标题:原形链

      本文链接:https://www.haomeiwen.com/subject/dleycxtx.html