this 继承

2017-08-21  本文已影响0人  leocz

1.apply call bind的作用与区别

apply call bind都是用来改变函数执行的上下文,也就是说,改变函数this的指向。
区别:
bind是返回对应函数,以便以后调用,而apply和call是立即调用,直接返回执行结果。apply于call的区别在于在接受参数的形式稍有区别。apply的调用形式是fn.apply(context,[argsArray]),接受数组形式的参数。call的调用形式是fn.call(context,arg1,arg2...)
eg.

bind

var obj1={
  name:"xiaoming",
  fn:function(){
    console.log(this.name)
  }
}
var obj2 = {name:xiaohu}
var fn2 = obj1.fn.bind(obj2);
fn2()   //xiaohu
call和apply

数组中没有比较大小的方法
var arr = [1,2,3,4];
var arrMax = Math.max.apply(null,arr);//至于为什么传null,这里的结果与this无关,无论传什么都不会影响结果

利用数组的join方法拼接字符串
function joinStr(){
    return [].join.call(arguments,'');
}
//join用法   var arr=[a,b,c]  arr.join('-')   //a-b-c
var str = joinStr('a','b','c');   //abc

2.代码输出

eg.1

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

eg.2

func()         //window   首先函数申明提升,this指向window
function func(){
  alert(this)
}

eg.3

document.addEventListener("click",function(e){
  console.log(this);
  setTimeout(function(){
    console.log(this)
  },200)
},false)
// document    事件中,this指向被绑定的dom对象
//window      setTimeout中的this指向window

eg.4

var john = {
  firstName : "John"
}

function func(){
  alert(this.firstName)
}
func.call(john)      //john  call把func的执行上下文改到john中

eg.5 如有问题就修改

var module={
  bind: function(){
    $btn.on('click',function(){
      console.log(this) // this指什么     
      this.showMsg();
    })
  },
  showMsg: function(){
    console.log('小明')
  }
}
// this指$btn  $btn并无showMsg方法,this在作为对象的方法调用的时候指向这个上级对象,所以可以采取两种方法

方法1
在this指向改变前,先把需要的this保存下来
var module={
  bind: function(){
    var _this = this     //_this就吧module保存下来了
    $btn.on('click',function(){
      console.log(this)    // this指什么     
      _this.showMsg();  
    })
  },
  showMsg: function(){
    console.log('小明')
  }
}
方法二
用bind把this的指向重新指向module
var module={
  bind: function(){
    $btn.on('click',function(){
      console.log(this) // this指什么     
      this.showMsg();
    }.bind(this))
  },
  showMsg: function(){
    console.log('小明')
  }
}

3.解释代码中Person,prototype,_proto,p,construtor之间的关联

function Person(name){
  this.name = name;
}
Person.prototype.sayName =function(){
  console.log("my name is :" + this.name)
}
var p = new Person("若愚")
p.sayName()
原型.png

4.对对象p调用p.toString() ,画出这一过程的原型图,解释原型链

也如上图,p是是Person的一个实例,每一个Person的实例都有proto,
指向Person的原型链Prototype,Person.prototype中的construtor指向函数Person,Person也是一个对象,所以Proson.prototype.proto指向了对象,而Object中就有toString()方法。

在调用p.toString()的时候,首先会现在实例p中寻找toString(),没找到就在proto,也就是Person.prototype中寻找,还没找到,就继续向原型方向p.proto.proto中寻找,找到了,拿出来使用。

5.对str做拓展,实现获取字符串中出现频率最高的字符

String.prototype.getMostOfften = function(){
  var obj = {},
      maxTime = 0,
      tarLetter;  
  for(var i=0; i<this.length; i++){
    var key = this[i]
    if (!obj[key]) {
         obj[key] = 1;
     } else {
          obj[key]++;
    }
  }

  for(key in obj){
    if(obj[key] > maxTime){
      maxTime = obj[key]
      tarLetter = key;
    }
  }
   return tarLetter;
}
var str = "ahbbccdeeddddfg";
var ch = str.getMostOfften();

console.log(ch) // d   5ci

6.instanceOf有什么用?内部逻辑如何实现?

instanceOf用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性

内部逻辑:沿着原型链向上查找,查找对象的原型链上的 __ proto __ 属性是否是某个构造函数的prototype属性,若存在则返回true,若查找到顶端也没找到则返回false。

7.继承有什么作用?

继承可以使子类共享父类的属性和方法,覆盖和扩展父类的属性和方法

8.两种写法的代码区别

//fangfa1
function People(name,sex){
  this.name = name;
  this.sex = sex;
  this.printName = function(){
    console.log(this.name);
  }
}
var p1 = new People("小明",18)
var p2 = new People("xiaohu",19)
console.log(p1.printName==p2.printName) //false

printName()是在每创建一个实例的时候都会创建一遍,所以二者并不相等

//fangfa2
function Person(name,sex){
  this.name = name;
  this.sex = sex;
}
Person.prototype.printName = function(){
  console.log(this.name)
}
var p1 = new Person("小虎",20)
var p1 = new Person("xiaoming",20)

console.log(p1.printName==p2.printName) // true
二者相等,证明二者指向了同一个函数,printName这一函数制备创建了一遍,是公用的。可节省内存。

9.Object.create有什么用?兼容性

Object.create是在ES5中规定的 ,作用是使用指定的原型对象及其属性去创建一个新的对象,IE9以下无效。

Object.create(proto, [ propertiesObject ])


//Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

Shape.prototype.move = function(x, y) {
    this.x += x;
    this.y += y;
    console.info("Shape moved.");
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); //call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

console.log('Is rect an instance of Rectangle?',
  rect instanceof Rectangle); // true
console.log('Is rect an instance of Shape?',
  rect instanceof Shape); // true

rect.move(1, 1); //Outputs, "Shape moved."

10.hasOwnProperty有什么用?怎么用

hasOwnProperty() 方法会返回一个布尔值,指示对象是否具有指定的属性作为自身(不继承)属性。

o = new Object();
o.prop = 'exists';

function changeO() {
  o.newprop = o.prop;
  delete o.prop;
}

o.hasOwnProperty('prop');   // 返回 true
changeO();
o.hasOwnProperty('prop');   // 返回 false

11.代码中的call作用什么?

function Person(name,sex){
  this.name = name;
  this.sex = sex;
}
function Male(name,sex,age){
  Person.call(this,name,sex) // 这里的call把Male函数里的this传递给Person,作为Person执行的上下文,这样Male也拥有自己的name和sex属性。
  this.age = age;
}

12.实现继承

function Person(name,sex){
  this.name = name
  this.sex = sex
}
Person.prototype.getName = function(){
  console.log("my name is " + this.name)
}
Person.prototype.printName = function(){
  console.log("my name is " + this.name + " and I am " + this.age + " years old")
}
function Male(name,sex,age){
  Person.call(this,name,sex)
  this.age = age
}
Male.prototype.getAge = function(){
  console.log("I am " + this.age + "years old")
}

Male.prototype=Object.create(Person.prototype)
Male.prototype.__proto__.constructor = Male

var xiaoming = new Male('小明','男',18);
xiaoming.printName();
上一篇 下一篇

猜你喜欢

热点阅读