美文网首页
原型链、this与继承

原型链、this与继承

作者: 我不信这样也重名 | 来源:发表于2019-01-11 18:57 被阅读0次

    this


    一、apply、call 、bind的作用与区别

    • bind:返回一个新函数,并且使函数内部的this为传入的第一个参数
    var fn3 = obj1.fn.bind(obj1);
    fn3();
    
    • call/apply:调用一个函数,传入函数执行上下文及参数,第一个参数都是希望设置的this对象,不同之处在于call方法接收参数列表,而apply接收参数数组
    fn.call(context, param1, param2...)
    fn.apply(context, paramArray)
    
    fn2.call(obj1);
    fn2.apply(obj1);
    

    二、实例

    1. 以下代码输出什么?

    var john = { 
      firstName: "John" 
    }
    function func() { 
      alert(this.firstName + ": hi!")
    }
    john.sayHi = func
    john.sayHi() 
    

    输出结果为John: h1!
    这是由于john.sayHi()语句可被改写为john.sayHi.call(john),当其被调用时,函数体内部的this为对象john本身。

    2. 下面代码输出什么,为什么?

    func() 
    function func() { 
      alert(this)
    }
    

    输出window对象。
    因为func()是在全局作用域下被调用,其可被改写为window.func.call(window),函数内部thiswindow对象

    3. 下面代码输出什么?

    document.addEventListener('click', function(e){
        console.log(this);
        setTimeout(function(){
            console.log(this);
        }, 200);
    }, false);
    

    第一个console.log输出document对象,thisdocument本身;第二个输出window对象,因为setTimeout函数是在全局作用域下执行的

    4. 下面代码输出什么,why?

    var john = { 
      firstName: "John" 
    }
    
    function func() { 
      alert( this.firstName )
    }
    func.call(john) 
    

    输出John
    因为函数调用时用call方法指定了john对象

    5. 以下代码有什么问题,如何修改?

    var module= {
      bind: function(){
        $btn.on('click', function(){
          console.log(this) //this指什么
          this.showMsg();
        })
      },
    
      showMsg: function(){
        console.log('饥人谷');
      }
    }
    

    bind属性的$btn.on('click', function())函数内部的this指代$btn,因此无法调用showMsg()
    改动如下:

    var module= {
      bind: function(){
        var _this = this
        $btn.on('click', function(){
          console.log(this) //this指什么
          _this.showMsg();
        })
      },
    
      showMsg: function(){
        console.log('饥人谷');
      }
    }
    

    原型链


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

    instanceOf操作符可用于判断一个对象是不是某个类型的实例

    [1, 2, 3] instanceof Array; //true
    [1, 2, 3] instanceof Object; //true
    

    注意: instanceof运算符是用来检测constructor.prototype是否在参数object的原型链上

    function C() {} 
    function D() {} 
    var o = new C() 
    
    o instanceof C; //true,因为Object.getPrototypeOf(o) === C.prototype 
    o instanceof D; //false,因为D.prototype不在o的原型链上 
    

    二、实例

    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是构造体constructor,其构造了函数pp是其实例;
    Person.prototypePerson的原型对象;
    __proto__是p的原型链,指向Personprototype

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

    toString来自于Object.prototype
    我们通过函数定义了类Person,类(函数)自动获得属性prototype,而每个类的实例都会有一个内部属性__proto__,指向类的prototype.。
    因此p.__proto__ -> Person.prototype (->) Person.prototype.__proto__ -> Object.prototype (->) Object.prototype.__proto__ -> null就是原型链。

    原型图

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

    var str = 'ahbbccdeddddfg';
    var ch = str.getMostOften();
    console.log(ch); //d , 因为d 出现了5次
    

    代码如下:

    var str = 'ahbbccdeddddfg';
    String.prototype.getMostOften = function(){
      var tmp = {}
      for(var i=0; i<this.length; i++){
        if(!tmp[this[i]]){
          tmp[this[i]] = 1
        }else{
          tmp[this[i]]++
        }
      }
      var max = 0
      var idx = ''
      for(var i in tmp){
        if(max < tmp[i]){
          max = tmp[i]
          idx = i
        }
      }
      return idx+' ,因为'+idx+'出现了'+max+'次'
    }
    var ch = str.getMostOften();
    console.log(ch); //d , 因为d 出现了5次
    

    继承


    一、Object.create 有什么作用?

    Object.create(proto[, propertiesObject ])可以创建一个拥有指定原型和若干个指定属性的对象:

    • proto:一个对象,作为新创建对象的原型。或者为null。
    • propertiesObject:可选。该参数对象是一组属性与值,该对象的属性名称将是新创建的对象的属性名称,值是属性描述符(这些属性描述符的结构与Object.defineProperties()的第二个参数一样)。注意:该参数对象不能是 undefined,另外只有该对象中自身拥有的可枚举的属性才有效,也就是说该对象的原型链上属性是无效的。
    function Male(name, sex, age){
        Person.call(this, name, sex);
        this.age = age;
    }
    
    Male.prototype = Object.create(Person.prototype);
    
    Male.prototype.printAge = function(){
        console.log(this.age);
    };
    

    二、hasOwnProperty有什么作用?给出范例

    hasOwnPerpertyObject.prototype的一个方法,可以判断一个对象是否包含自定义属性而不是原型链上的属性,hasOwnProperty是JavaScript中唯一一个处理属性但是不查找原型链的函数

    m.hasOwnProperty('name'); // true
    m.hasOwnProperty('printName'); // false
    Male.prototype.hasOwnProperty('printAge'); // true
    

    三、实例

    1. 下面两种写法有什么区别?

    //方法1
    function People(name, sex){
        this.name = name;
        this.sex = sex;
        this.printName = function(){
            console.log(this.name);
        }
    }
    var p1 = new People('饥人谷', 2)
    
    //方法2
    function Person(name, sex){
        this.name = name;
        this.sex = sex;
    }
    
    Person.prototype.printName = function(){
        console.log(this.name);
    }
    var p1 = new Person('若愚', 2);
    
    • 方法1中,namesexprintName均是p1自身的属性
    • 方法2中,namesexp1自身的属性,而printNamep1的原型对象Person.prototype的自定义对象,p1可以继承其属性与方法,从而节约代码量,提高性能。

    2. 如下代码中call的作用是什么?

    function Person(name, sex){
        this.name = name;
        this.sex = sex;
    }
    function Male(name, sex, age){
        Person.call(this, name, sex);    //这里的 call 有什么作用
        this.age = age;
    }
    

    call调用Person方法,指定Person方法中的thisMale,并传入参数sexage

    3. 补全代码,实现继承

    function Person(name, sex){
        // todo ...
    }
    
    Person.prototype.getName = function(){
        // todo ...
    };    
    
    function Male(name, sex, age){
       //todo ...
    }
    
    //todo ...
    Male.prototype.getAge = function(){
        //todo ...
    };
    
    var hugner = new Male('饥人谷', '男', 2);
    hunger.printName();
    

    代码如下:

    function Person(name, sex){
      this.name = name
      this.sex = sex
    }
    
    Person.prototype.getName = function(){
      return this.name
    };    
    
    function Male(name, sex, age){
      Person.call(this, name, sex)
      this.age = age
    }
    
    Person.prototype.printName = function(){
      console.log(this.getName())  
    }
    
    Male.prototype = Object.create(Person.prototype)
    
    Male.prototype.getAge = function(){
      return this.age
    };
    
    var hunger = new Male('饥人谷', '男', 2);
    hunger.printName();
    

    相关文章

      网友评论

          本文标题:原型链、this与继承

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