this 原型链 继承

2018-10-31  本文已影响0人  毕子歌

问题1: apply、call 、bind有什么作用,什么区别
apply()和call()都可以在特定的作用域中调用函数,实际上等于设置函数体内this对象的值
apply()方法接受两个参数:一个是在其中运行函数的作用域,另一个是参数数组。其中第二个参数可以是Array的实例,也可以是arguments对象。call()不同的地方在于必须明确传入的每一个参数
bind()方法会创建一个函数的实例,其this值会被绑定带传给bind()函数的值
apply和call是直接调用,而bind方法可以之后调用。
问题2: 以下代码输出什么?

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

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

func() 
function func() { 
  alert(this)  //[object Window],this没指定时默认为Window对象
}

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

var john = { 
  firstName: "John" 
}

function func() { 
  alert( this.firstName ) //输出John,若没有.call输出undefined,call方法将this设置为john对象
}
func.call(john)

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

var module= {
  bind: function(){
    $btn.on('click', function(){
      console.log(this) //this指什么  this指的是被绑定事件的$btn对象
      this.showMsg();   
    })
  },
  
  showMsg: function(){
    console.log('饥人谷');
  }
}

修改

var module= {
  bind: function(){
    var _this = this
    $btn.on('click', function(){
      console.log(this) 
      _this.showMsg();   
    })
  },
  
  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();

prototype是Person的原型对象,prototype的constructor构造函数属性指向Person,p是Person的一个实例,p.__proto__指向Person.prototype

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

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

String.prototype.getMostOften = function(){
  var letter = {}
  , n 
  for( var i=0 ; i<this.length; i++){
    n = this[i]
    if(!letter[n]){
      letter[n] = 1;
    }else{
      letter[n]++
    }    
  }
  var val
     ,times = 0
  for(key in letter){
    if(letter[key]>times){
      times = letter[key]
      val = key
    }
  }
  return '字符串中出现次数最多的字母是'+val+'次数为'+times

console.log(letter)
}
var str = 'ahbbccdeddddfg';
var ch = str.getMostOften();
console.log(ch)

问题10: instanceOf有什么作用?内部逻辑是如何实现的?
instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性。
沿着对象的__proto__这条线来找,同时沿着函数的prototype这条线来找,如果两条线能找到同一个引用,即同一个对象,那么就返回true。如果找到终点还未重合,则返回false。
问题11:继承有什么作用?
继承指一个对象可以直接使用另一个对象的属性和方法

上一篇 下一篇

猜你喜欢

热点阅读