高级2-this_原型链_继承

2017-01-18  本文已影响0人  Maggie_77

this 相关问题

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

Javascript的每个Function对象中有一个apply方法:
function.apply([thisObj[,argArray]])
还有一个类似功能的call方法:
function.call([thisObj[,arg1[, arg2[, [,.argN]]]]])

更简单地说,apply和call功能一样,只是传入的参数列表形式不同:如 func.call(func1,var1,var2,var3) 对应的apply写法为:func.apply(func1,[var1,var2,var3])
也就是说:call调用的为单个,apply调用的参数为数组

function sum(a,b){
    console.log(this === window);//true
    console.log(a + b);
 }
 sum(1,2);
 sum.call(null,1,2);
 sum.apply(null,[1,2]);

作用  

var info = 'tom';
function foo(){   
    //this指向window 
    var info = 'jerry';
    console.log(this.info);   //tom
    console.log(this===window)  //true
}
foo(); 
foo.call();
foo.apply();
var obj = {
        info:'spike'
}
foo.call(obj);    //这里foo函数里面的this就指向了obj
foo.apply(obj);
var arr = [123,34,5,23,3434,23];
//方法一
var arr1 = arr.sort(function(a,b){
    return b-a;
});
console.log(arr1[0]);
//方法二
var max = Math.max.apply(null,arr)   //借用别的对象的方法
console.log(max);

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

var john = { 
  firstName: "John" 
}
function func() { 
alert(this.firstName + ": hi!")
}
john.sayHi = func
john.sayHi()  // John: hi!,this指向调用sayHi()的john对象

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

func() 

function func() { 
  alert(this)    //window,因为在函数被直接调用时this绑定到全局对象。在浏览器中,window 就是该全局对象
}

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

document.addEventListener('click', function(e){
    console.log(this);  //#document.
                        //在事件处理程序中this代表事件源DOM对象
    setTimeout(function(){
        console.log(this);  //window.
                            //setTimeout、setInterval这两个方法执行的函数this也是全局对象
    }, 200);
}, false);

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

var john = { 
  firstName: "John" 
}

function func() { 
  alert( this.firstName )
}
func.call(john)    //John
                   //call(john)传入了john这个执行上下文,this指向john这个对象

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

var module= {
  bind: function(){
    $btn.on('click', function(){
      console.log(this) //this指$btn
      this.showMsg();
    })
  },
  
  showMsg: function(){
    console.log('饥人谷');
  }
}
//修改后:
var module= {
  bind: function(){
     var cur = this;  //将this代表的module存到cur
    $btn.on('click', function(){
      console.log(this) //$btn
      cur.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();
Person.prototype.__proto__ === Object.prototype;
Person.prototype.constructor == Person

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

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

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

代码如下:

//方法一:
String.prototype.getMostOften = function(){
    var obj = {};
    for(var i=0,k;i<this.length;i++){
        k = this[i];
        if(obj[k]){
            obj[k]++
        }else{
            obj[k] = 1
        }
    }

    var max = 0,key;
    for(var k in obj){
        if(obj[k]>max){
           max = obj[k];
           key = k;
        }
     }

    return key;
}
//方法二:
String.prototype.getMostOften = function(){
    var arr = this.split("");
    var result = arr.reduce(function(allLetters,letter){
        if(allLetters[letter]){
            allLetters[letter]++
        }else{
            allLetters[letter] = 1
        }
    
        return allLetters;          
    },{});
  var max = 0,k;
        for(var key in result){
            if (result[key]>max){
                max = result[key];
                k = key
            }
        }
    return k;
}
var str = 'ahbbccdeddddfg';
var ch = str.getMostOften();
console.log(ch); //d 

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

function instanceOf(obj,fn){
    var oldpro = obj.__proto__;
    while(oldpro){
    if(oldpro === fn.prototype){
        return true;
    }else{
        oldpro = oldpro.__proto__;
    }
    }
    return false;
}

继承相关问题

问题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)

//方法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方法,方法1的printName方法是在函数Person实例对象里的,方法2是在Person的prototype对象上的。当再创建一个Person实例对象的时候,方法1又将会再创建一个printName方法,占用新的内存,而方法2将一个公用的printName方法写在原型上,当对象要使用该方法只需到原型链里调用就可以了,达到节省内存的效果。

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

function Person(name, age){
  this.name = name;
  this.age = age;
}
Person.prototype.sayName = function(){
  console.log(this.name);
}
function Male(name, age, sex){
  Person.call(this, name, age);
  this.sex = sex;
}
// Male.prototype = new Person(); //该方法同下,代替不兼容Object.create()的使用场景
Male.prototype = Object.create(Person.prototype);
Male.prototype.constructor = Male;
Male.prototype.sayAge = function(){
    console.log(this.age);
};
var p1 = new Male('hunger', 20, 'nan');
p1.sayName();//hunger
p1.sayAge();//20

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

p1.hasOwnProperty('name');//true
p1.hasOwnProperty('sayName');//false
Male.prototype.hasOwnProperty('sayAge');//true

问题15:如下代码中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;
}

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

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

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

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

Male.prototype = Object.create(Person.prototype);
Male.prototype.constructor = Male;
Male.prototype.getAge = function(){
    console.log(this.name);
};

var ruoyu = new Male('若愚', '男', 27);
ruoyu.getName();//若愚
上一篇 下一篇

猜你喜欢

热点阅读