美文网首页
web前端-深入(2)-this_原型链_继承

web前端-深入(2)-this_原型链_继承

作者: 抚年华轻过 | 来源:发表于2017-08-16 16:37 被阅读0次

this 相关问题

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

  1. bind:返回一个函数,传入第一个参数作为函数的this,第二个开始作为函数的参数
var obj1 = {
    name: 'Byron',
    fn : function(){
        console.log(this);
    }
};
obj3={a: 3};
var fn3=obj1.fn.bind(obj3);
fn3();  //obj3,this被替换了obj3

document.addEventListener('click', function(e){
    console.log(this);                    //document
    setTimeout(function(){
        console.log(this);            //document
    }.bind(this), 200);
}, false);
  1. call:调用一个函数,传入第一个参数作为函数的this,随后的参数作为argumenst传入
var value=100;
function fn(a,b){
  console.log(this.value+a+b);
}
var obj={
  value:200
}
fn(3,5);   //108
fn.call(obj,3,5);   //208
  1. apply:调用一个函数,传入第一个参数作为函数的this,第二个参数为一个数组,数组内为要传入的参数
var value=100;
function fn(a,b){
  console.log(this.value+a+b);
}
var obj={
  value:200
}
fn(3,5);   //108
fn.apply(obj,[3,6]);  //209

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

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

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

func() 
function func() { 
  alert(this)
}
//输出window对象,func()相当于window.func(),this指向的是window对象

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

document.addEventListener('click', function(e){
    console.log(this);
    setTimeout(function(){
        console.log(this);
    }, 200);
}, false);
//->  #document
//绑定 document 之后,事件发生运行的函数里的 this 指向绑定的对象

//-> [object Window]
//setTimeout,setInterval中的延迟执行代码中的 this 永远都指向 window

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

var john = { 
  firstName: "John" 
}

function func() { 
  alert( this.firstName )
}
func.call(john)   //John
//本来函数里面的this指向的是window,但是函数调用了call()函数,函数里的this指向了john

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

var module= {
  bind: function(){
    $btn.on('click', function(){
      console.log(this) //this指什么
      this.showMsg();
    })
  },
  
  showMsg: function(){
    console.log('Ethan');
  }
}
//因为this在$btn绑定事件函数中,所以this指向了$btn对象
//修改
var module= {
  bind: function(){
    $btn.on('click', function(){
      console.log(this)
      this.showMsg();
    }.bind(this))
  },
  
  showMsg: function(){
    console.log('Ethan');
  }
}

原型链相关问题

问题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是构造函数,p是Person的实例
//Person.prototype是Person构造函数的原型对象
//Person.prototype里的constructor属性指向Person
Person.prototype.constructor===Person   //true
//_proto_是p实例里的属性,指向Person.prototype
p._proto_===Person.prototype   //true

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

  1. 原型链:对象的属性和方法,有可能是定义在自身,也有可能是定义在它的原型对象。由于原型对象本身也是对象,也有自己的原型,依次类推,形成了一条原型链(prototype chain)。
  2. 如果一层层地上溯,所有对象的原型最终都可以上溯到Object.prototype,即Object构造函数的prototype属性指向的那个对象。Object.prototype对象的原型为null,而null没有原型对象
  3. 「原型链」的作用是,读取对象的某个属性时,JavaScript 引擎先寻找对象本身的属性,如果找不到,就到它的原型去找,如果还是找不到,就到原型的原型去找。如果直到最顶层的Object.prototype还是找不到,则返回undefined

问题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;i<this.length;i++){
    if(obj[this[i]]) {
      obj[this[i]]++;
    }
    else obj[this[i]]=1;
  }
  var num=0; str1='';
  for(var key in obj){
    if(obj[key]>num) {
      num=obj[key]; str1=key;
    }
  }
  return str1;
}

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

//instanceOf 的作用是用来判断对象是否是另一个对象的实例,并返回布尔值。
function _instanceOf(obj,fn){
    var proto=obj.__proto__;
    do{
        if(proto===fn.prototype){
            return true;
        }else{
            proto=proto.__proto__
        }
    }while(proto)
    return false;
}
var arr=[1,2,3];
_instanceOf(arr,Array);//true
_instanceOf(arr,Object)//true

继承相关问题

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

  1. 子类拥有父类的属性和方法,不需要重复写代码,修改时也只需修改一份代码
  2. 可以重写和扩展父类的属性和代码,又不影响父类本身

问题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 方法定义在构造函数 People 内,每次new一个实例出来,都会先声明一个函数,
//把函数放入printName属性中,虽然不会报错,但是每次声明的都是一样的函数,增加了代码量。

//方法二:将 printName 方法定义在 Person 的原型对象内,这样new一个实例出来,
//即使内部没有定义,还是能够通过原型链得到此方法,节约了内存。

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

  1. Object.create() 方法创建一个拥有指定原型和若干个指定属性的对象。
    Object.create(proto, [ propertiesObject ]):第一个参数必选,是一个对象的原型,第二个开始参数可选,为属性对象
  2. Object.create是 ES5 中规定的,IE9 以下无效。
function grandfather(name) {
    this.name = name;
};

grandfather.prototype.say = function() {
    console.log('My name is ' + this.name);
};

function father(name) {
    grandfather.call(this,name);  //调用grandfather,并把函数内的this替换了
};

father.prototype = Object.create(grandfather.prototype);  //把father.prototype._proto_指向了grandfather.prototype
father.prototype.constructor = father;  //设置father.prototype.constructor

var p1 = new father('Ethan');

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

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

function P(name){this.name=name;}
P.prototype.say=function(){console.log(this.name);}
var obj=new P("Ethan");
obj. hasOwnProperty("name");  //true
obj. hasOwnProperty("say");  //false

问题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;
}
//call的作用:调用Person函数,并将Male的this传入,并且传入name和sex两个参数

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

function Person(name, sex){
    // todo ...
}

Person.prototype.getName = function(){
    // todo ...
};    

function Male(name, sex, age){
   //todo ...
}

//todo ...
Male.prototype.getAge = function(){
    //todo ...
};

var ruoyu = new Male('若愚', '男', 27);
ruoyu.printName();
function Person(name, sex){
    this.name=name;
    this.sex=sex;
}

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

function Male(name, sex, age){
   this.age=age;
  Person.call(this,name,sex);  //这个必须有,不然实例对象没有sex和name属性
}

Male.prototype=Object.create(Person.prototype);
Male.prototype.constructor=Male;
Male.prototype.getAge = function(){
    console.log(this.age);
};
Male.prototype.printName=function(){
  console.log(this.name);
}
var ruoyu = new Male('若愚', '男', 27);
ruoyu.printName();

笔记

1、this
  1. 全局下this
console.log(this);  //window
  1. 内部函数this
function fn(){
  funciton fn1(){
    console.log(this);
  }
}
fn();   //window,在当前作用域下找不到this,直接往父作用域找,直到找到为止
  1. setTimeout(),setInterval()的this特殊性
document.addEventListener('click', function(e){
    console.log(this);                    //document
    setTimeout(function(){
        console.log(this);            //window
    }, 200);
}, false);
  1. 构造函数
function Person(name){
  this.name=name;
}
Person.prototype.print=function(){
  console.log(this.name);
}
var person1=new Person("Ethan");
//1、创建了一个空对象作为this
//2、this.proto指向构造函数的prototype
//3、运行构造函数
//4、返回this(如果构造函数里没有return,若存在return引用类型,则返回return后的值)
  1. 作为对象方法调用
//初始
var obj1 = {
    name: 'Byron',
    fn : function(){
        console.log(this);
    }
};
obj1.fn();   //obj1
//演变1
var obj1 = {
    name: 'Byron',
    obj2:{
      fn:function(){
          console.log(this);
      }
    }
};
obj1.obj2.fn();    //obj2
//演变2
var obj1 = {
    name: 'Byron',
    fn : function(){
        console.log(this);
    }
};
var fn2=obj1.fn;
fn2();    //window,相当于window.fn2();
  1. 转换this方法
//Function.prototype.bind();替换this,但是不会执行函数
var obj1 = {
    name: 'Byron',
    fn : function(){
        console.log(this);
    }
};
obj3={a: 3};
var fn3=obj1.fn.bind(obj3);
fn3();  //obj3,this被替换了obj3

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

//call(arg1,arg2,arg3...);第一个参数为替换this,第二个开始是传给函数的参数,并执行函数
//apply(arg1,[arg2,arg3...]);第一个参数为替换this,第二个开始是数组,数组里的值传给函数的参数,并执行函数
var value=100;
function fn(a,b){
  console.log(this.value+a+b);
}
var obj={
  value:200
}
fn(3,5);   //108
fn.call(obj,3,5);   //208
fn.apply(obj,[3,6]);  //209

var arr=[1,3,9,7,4];
//Math.max(1,3,9,7,4);
console.log(Math.max.apply(null,arr));   //利用apply函数把数组里的值取出并传递给Math.max(),使得函数可以执行

function joinStr(){
  //arguments.join("-");不能这么用,因为arguments为对象,没有join方法
  var str=Array.prototype.join.call(arguments, "-"); 
  var temp=Array.prototype.join.bind(arguments);
  var str2=temp("-");
  console.log(str);
  console.log(typeof str);
 console.log(str2);
  console.log(typeof str2);
}
joinStr(1,2,"a");
  1. 三种变量
//实例变量:(this)类的实例才能访问到的变量
//静态变量:(属性)直接类型对象能访问到的变量
//私有变量:(局部变量)当前作用域内有效的变量
function ClassA(){
    var a = 1; //私有变量,只有函数内部可以访问
    this.b = 2; //实例变量,只有实例可以访问
}
ClassA.c = 3; // 静态变量,也就是属性,类型访问
console.log(a); // error
console.log(ClassA.b) // undefined
console.log(ClassA.c) //3

var classa = new ClassA();
console.log(classa.a);//undefined
console.log(classa.b);// 2
console.log(classa.c);//undefined

相关文章

  • web前端-深入(2)-this_原型链_继承

    this 相关问题 问题1: apply、call 、bind有什么作用,什么区别 bind:返回一个函数,传入第...

  • web前端面试之js继承与原型链(码动未来)

    web前端面试之js继承与原型链(码动未来) 3.2.1、JavaScript原型,原型链 ? 有什么特点? 每个...

  • this_原型链_继承

    1.apply、call 、bind有什么作用,什么区别 bind:返回一个新函数,并且使函数内部的this为传入...

  • this_原型链_继承

    this 相关问题 1: apply、call 、bind有什么作用,什么区别? 在JS中,这三者都是用来改变函数...

  • this_原型链_继承

    this 相关问题 1.apply、call 、bind有什么作用,什么区别 fn.apply(context ,...

  • this_原型链_继承

    this 相关问题 问题1: apply、call 、bind有什么作用,什么区别 在 javascript 中,...

  • this_原型链_继承

    问题1: apply、call 、bind有什么作用,什么区别 改变函数执行时的上下文,具体的就是指绑定this指...

  • this_原型链_继承

    1: apply、call 、bind有什么作用,什么区别 作用:改变函数体内 this 的指向 区别:对于 ap...

  • this_原型链_继承

    1.apply、call 、bind有什么作用,什么区别 call apply的作用:调用一个函数,传入函数执行上...

  • this_原型链_继承

    this 相关 1. apply、call 、bind有什么作用,什么区别 apply、call、bind可以改变...

网友评论

      本文标题:web前端-深入(2)-this_原型链_继承

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