高级2

this 相关问题

问题1: apply、call 、bind有什么作用,什么区别

  • bind
    Function.prototype.bind()方法创建一个新的函数, 当被调用时,将其this关键字设置为提供的值

  • call
    Function.prototype.call()方法调用一个函数, 其具有一个指定的this值
    call方法的参数,应该是一个对象。如果参数为空、null和undefined,则默认传入全局对象。
    call方法还可以接受多个参数。call的第一个参数就是this所要指向的那个对象,后面的参数则是函数调用时所需的参数。

  • apply
    apply() 方法调用一个函数, 其具有一个指定的this值,以及作为一个数组(或类似数组的对象)提供的参数。

该方法的作用和 apply() 方法类似,只有一个区别,就是call()方法接受的是若干个参数的列表,而apply()方法接受的是一个包含多个参数的数组。

问题2: 以下代码输出什么?

var john = { 
  firstName: "John" 
}
function func() { 
  alert(this.firstName + ": hi!")
}
john.sayHi = func
john.sayHi() 
// john.sayHi()的this指向john = {}
// 输出 alert(John:hi!)

问题3: 下面代码输出什么,为什么

func() 
function func() { 
  alert(this)
}
// 函数被直接调用,this为全局对象window
//输出 alert(window)

问题4:下面代码输出什么

document.addEventListener('click', function(e){
    console.log(this);  // this指向document
    setTimeout(function(){
        console.log(this); // this指向全局对象window
    }, 200);
}, false);

问题5:下面代码输出什么,why

var john = { 
  firstName: "John" 
}

function func() { 
  alert( this.firstName ) //输出 alert(john)
}
func.call(john)     
// Function.call(thisArg, arg1, arg2, ...) 
// 将thisArg作为指定的this值传入func()

问题6: 以下代码有什么问题,如何修改

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


// 修改方案1: 讲需要用到的this提前保存起来

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


// 修改方案2: bind()绑定this

var module= {
  bind: function(){
    $btn.on('click', function(){
      console.log(this) //this指$btn
      _his.showMsg();   // $btn没有showMsg方法
    }).bind(this)
  },
  
  showMsg: function(){
    console.log('饥人谷');
  }
}

原型链相关问题

问题7:有如下代码,解释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();

// p是构造函数Person的实例,p的__proto__属性指向构造函数Person的prototype属性
// prototype属性下的constructor属性指向构造函数Person


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

TIM截图20170829225439.png

如图所示:在调用p.toString()的时候,首先会在实例p中寻找toString(),如果 找不到就去proto(Person.prototype)即实例p的原型构造函数Person中寻找,如果还没找到,就继续向原型方向构造函数Person的原型中中寻找,找到之后拿出来使用。

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

        var str = 'ahbbccdeddddfg'
        var ch = str.getMostOften()

        String.prototype.getMostOften = function () {

            var dict = {}
            for (var i = 0; i < this.length; i++) {
                if (dict[this[i]]) {
                    ++dict[this[i]]
                } else {
                    dict[this[i]] = 1
                }
            }
            console.log(dict)
            var count = 0
            var maxValue
            for (key in dict) {
                if (dict[key] > count) {
                    maxValue = key
                    count = dict[key]
                }
            }
            console.log(maxValue, count)
        }
        console.log(ch)

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

instanceof操作符,判断一个对象是不是某个类型的实例

通过判断 实例的proto === 构造函数的 prototype || 实例的proto.proto === 构造函数的 prototype || 实例的proto.proto.proto === 构造函数的 prototype
直到实例的proto.proto.proto为null, 如果都不相等,则该实例不是该类型的实例

继承相关问题

问题11:继承有什么作用?

继承是指一个对象直接使用另一对象的属性和方法。

问题12: 下面两种写法有什么区别?

//方法1
function People(name, sex){
    this.name = name;
    this.sex = sex;
    this.printName = function(){
        console.log(this.name);
    }
}
var p1 = new People('饥人谷', 2)
// 给构造函数绑定了printName的方法,每次创建的实例的printName都是指向新的内存空间,占用资源较多


//方法2
function Person(name, sex){
    this.name = name;
    this.sex = sex;
}

Person.prototype.printName = function(){
    console.log(this.name);
}
var p1 = new Person('若愚', 27);

// 给构造函数的原型绑定了printName的方法,每次创建的实例的printName都是通过继承其原型上的方法,不同的实例指向相同的内存空间,节省资源

问题13: Object.create 有什么作用?兼容性如何?

Object.create(proto, [ propertiesObject ]) 方法会使用指定的原型对象及其属性去创建一个新的对象。
var a = Object.create(obj1) 将obj1作为a的原型

ES5新增,IE9以下无效

问题14: hasOwnProperty有什么作用? 如何使用?

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

obj.hasOwnProperty(prop) 判断obj本身是否包含prop属性

function Person(name, sex){
    this.name = name;
    this.sex = sex;
}

Person.prototype.printName = function(){
    console.log(this.name);
}; 

var obj1 = new Person('cheney', 18)
console.log(obj1)

console.log(obj1.hasOwnProperty('name'))    // true
console.log(obj1.hasOwnProperty('sex'))     // true

console.log(obj1.hasOwnProperty('printName'))   // false

问题15:如下代码中call的作用是什么?

function Person(name, sex){
    this.name = name;
    this.sex = sex;
}
function Male(name, sex, age){
    Person.call(this, name, sex);    //把Male内部的this指定给函数Person,此时的this是通过构造函数new的实例,
                                     //将该实例指定为person的this之后,该实例就拥有的name和sex属性,
    this.age = age;
}

问题16: 补全代码,实现继承

function Person(name, sex){
    this.name = name
    this.sex = sex
}

Person.prototype.getName = function(){
    console.log("my name is " + this.name)
};    

function Male(name, sex, age){
   Person.call(this, name, sex)
   this.age = age
}

Male.prototype = Object.create(Person.prototype)
Male.prototype.construtor = Male

Male.prototype.getAge = function(){
    console.log("I am " + this.age + 'years old')
};



var ruoyu = new Male('若愚', '男', 27);
ruoyu.getName();

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容