What's this?

What's this?

由于运行期绑定的特性,JavaScript 中的 this 含义非常多,它可以是全局对象、当前对象或者任意对象,这完全取决于函数的调用方式

随着函数使用场合的不同,this的值会发生变化。但是有一个总的原则,那就是this指的是,调用函数的那个对象

作为函数调用

在函数被直接调用时this绑定到全局对象。在浏览器中,window 就是该全局对象

<script>
        var b =2
        console.log(this)//在全局作用域下,this代表window
        function fn1(){
         var b=1
          console.log(this);//window
          console.log(this.b) //2
         }
fn1();
</script>
<script>
function fn1(){
         var b=1
          console.log(this.b) //undefined
         }

fn1()
<script>
<script>
        var b =2
        function fn1(){
        b=1
          console.log(this);//window
          console.log(this.b) //1
         }
fn1();
</script>

在全局作用域下声明的变量,

var a =1 //  相当于window.a = 1 也等于this.a = 1

内部函数

函数嵌套产生的内部函数的this不是其父函数,仍然是全局变量

function fn0(){
    function fn(){
        console.log(this); //window
    }
    fn();
}

fn0();

setTimeout、setInterval

这两个方法执行的函数this也是全局对象

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

如果 想要setTimeout里面的this代表document

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

作为构造函数调用

所谓构造函数,就是通过这个函数生成一个新对象(object)。这时,this就指这个新对象

new 运算符接受一个函数 F 及其参数:new F(arguments...)。这一过程分为三步:

1.创建类的实例。这步是把一个空的对象的__proto__属性设置为 F.prototype 。
2.初始化实例。函数 F 被传入参数并调用,关键字 this 被设定为该实例。
3.返回实例。

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

var p1 = new Person('Byron');
var p2 = new Person('Casper');

p1.printName();//Byron
p2.printName();//Casper

作为对象方法调用

在 JavaScript 中,函数也是对象,因此函数可以作为一个对象的属性,此时该函数被称为该对象的方法,在使用这种调用方式时,this 被自然绑定到该对象

var obj1 = {
    name: 'Byron',
    fn : function(){
        console.log(this); //obj1
    }
};

obj1.fn();//谁调用,就指向谁(obj1)
var obj3 = {
    name:'lucas',
    obj1: {
    name: 'Brown',
    fn : function(){
        console.log(this); //obj1
    }
  }
}

obj3.obj1.fn(); //谁调用,就指向谁(obj3.obj1)

小陷阱

var fn2 = obj1.fn;
fn2(); //window
//函数调用只有一种形式func.call(context, p1, p2)
// 由于没有传 context
// 所以 this 就是 undefined
// 最后浏览器给你一个默认的 this —— window 对象

改变this指向的三个方法: bind,call,apply

不采用这三个方法可能会遇到这样的问题,采用这种方法调用this.user相当于window.usr,所以返回undefined。

var a = {
    user:"追梦子",
    fn:function(){
        console.log(this.user);
    }
}
var b = a.fn;
b(); //undefined

我们直接执行a.fn()是可以的

var a = {
    user:"追梦子",
    fn:function(){
        console.log(this.user);
    }
}
a.fn(); //追梦子

虽然这种方法可以达到我们的目的,但是有时候我们不得不将这个对象保存到另外的一个变量中,那么就可以通过以下方法。

使用call和apply设置this

call,apply,调用一个函数,传入函数执行上下文(context级this)及参数

fn.call(context, param1, param2...)
fn.apply(context, paramArray)

通过call或者apply方法,第一个参数都是设置希望this所指向的那个对象,即把fn添加期望运行的context环境中。
不同之处在于call方法接收参数列表,而apply接收参数数组。

var a = {
    user:"追梦子",
    fn:function(){
        console.log(this.user);
    }
}
var b = a.fn
b.call(a); /*也可以是 b.apply(a);*/

注意:如果call和apply的第一个参数写的是null,那么this指向的是window对象

使用bind设置this

bind方法和call、apply方法有些不同,但它们都可以用来改变this的指向。

Function.prototype.bind(context, param1, param2...)

任何函数都有bind这样一个方法。bind,返回一个新的函数,函数内部的this为你传入的第一个参数。
仿照之前call和apply的写法,我们使用bind

var a = {
    user:"追梦子",
    fn:function(){
        console.log(this.user); //追梦子
    }
}
var b = a.fn;
b.bind(a);

发现代码没有被打印,对,这就是bind和call、apply方法的不同,实际上bind方法返回的是一个修改过后的函数。执行该函数看看。

var a = {
    user:"追梦子",
    fn:function(){
        console.log(this.user); //追梦子
    }
}
var b = a.fn;
b.bind(a)(); // "追梦子"

同样bind也可以有多个参数,并且参数可以执行的时候再次添加

var a = {
    user:"追梦子",
    fn:function(e,d,f){
        console.log(this.user); 
        console.log(e,d,f); 
    }
}
var b = a.fn;
var c = b.bind(a,10,44);
c(33);

更多例子

bind的例子

var obj3={
        name: 'apple'
    }
var obj1={
    name: 'Brown',
    fn : function(){
        console.log(this);
    }
}

var fn3 = obj1.fn.bind(obj3)
fn3() 
//[object Object] {
//  name: "apple"
//}
//此时的this就是你传入的第一个参数obj3
想要setTimeout里面的this代表document的另一种实现方式
#通过bind绑定的this是setTimeout函数外部的this,即document
document.addEventListener('click', function(e){
    console.log(this);//document
    setTimeout(function(){
        console.log(this); //document
    }.bind(this), 200);
}, false);

call和apply设置this的例子

var value =100
var obj4 = {
    value:200
}
function fn4(a,b){
    console.log(this.value+a+b)
}
fn4(3,4) //107
fn4.call(obj4,3,4) //207
fn4.apply(obj4,[3,4]) //207

应用

var arr = [1,2,7,4]
//Math.max(1,2,7,4)
console.log(Math.max.apply(null,arr)) //7
function joinStr(){
    //console.log(Array.prototype.join.call(arguments,'-'))
    var join = Array.prototype.join.bind(arguments)
    console.log(join('-'))
}
joinStr('a','b','c') //a-b-c

arguments

1.在函数调用时,会在函数内部自动生成一个名为 arguments的隐藏对象
2.为类数组对象,可以使用[]运算符获取函数调用时传递的实参
3.只有函数被调用时,arguments对象才会创建,未调用时其值为null

unction fn5(name, age){
     console.log(arguments);// ["Byron", 20]
     name = 'XXX';
     console.log(arguments); //["XXX", 20]
     arguments[1] = 30;
     console.log(arguments); //["XXX", 30]
 }
 fn5('Byron', 20);

函数的三种变量

  • 实例变量:(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

原型与原型链

回顾一下类、实例、prototype、__proto__的关系


1.我们通过函数定义了类Person,类(函数)自动获得属性prototype
2.每个类的实例都会有一个内部属性__proto__,指向类的prototype属性

因为prototype本质上是个类Object的实例,所以prototype也和其它实例一样也有个__proto__内部属性,指向其类型Object的prototype

类型

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

function Person(nick, age){
    this.nick = nick;
    this.age = age;
}
Person.prototype.sayName = function(){
    console.log(this.nick);
}

var p1 = new Person();

判断p1是不是Person类型的实例,

p1 instanceof Person //true
//其中经历了一下过程
//先查找p1._proto_ === Person.prototype
//如果上面查找未成功,再查找p1._proto_._proto_ === Preson.prototype
原型链

继承

继承是指一个对象直接使用另一对象的属性和方法。
JavaScript并不提供原生的继承机制,但可以自己实现

只要实现了两点的话就可以说我们实现了继承
1.得到一个类的属性
2.得到一个类的方法

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

Person.prototype.sayName = function(){
    console.log('My name is'+this.name);
};
Person.prototype.walk = function(){
    console.log(this.name+'is walking')
}
function Student(name, age,sex){
}
Student.prototype.doing = function(){
    console.log("I am studying");
};

var s = new Student('hunger',2,'boy')
#问题:怎么让Studen继承Person的属性name, age和方法sayName呢?

属性获取

对象属性的获取是通过构造函数的执行,我们在一个类中执行另外一个类的构造函数,就可以把属性赋值到自己内部,但是我们需要把环境改到自己的作用域内,可以借助函数call或bind

function Student(name, age,sex){
    Person.call(this,name,age)
    //Person.bind(this,name,age)
    this.sex = sex
}

方法获取

Object.create(proto)
创建一个新的对象,新对象的原型就是传入的参数

类的方法都定义在了prototype里面,所以只要我们把子类的prototype改为父类的prototype的备份就好了

Student.prototype = Object.create(Person.prototype)

这里我们通过Object.createclone了一个新的prototype而不是直接把Person.prtotype直接赋值,因为引用关系,这样会导致后续修改子类的prototype也修改了父类的prototype,因为引用关系修改的是同一个值,如果是直接赋值就等于是Student.prototype.__proto__ = Person.prototype

Object.create是ES5方法,之前版本通过遍历属性也可以实现浅拷贝

注意:对子类添加新的方法,必须在修改其prototype之后,否则会被覆盖掉

最后需要重新指定一下constructor属性到自己的类型

所以,最后写为

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

Person.prototype.sayName = function(){
   console.log('My name is'+this.name);
};
Person.prototype.walk = function(){
   console.log(this.name+'is walking')
}
var p = new Person('ruoyu',100)

function Student(name, age,sex){
   //把属性拿过来
   Person.call(this,name,age)
   //Person.bind(this,name,age)
   this.sex = sex
}
//方法拿过来
Student.prototype = Object.create(Person.prototype)
Student.prototype.constructor = Student //重新指定一下constructor属性到自己的类型 ,不然Student.prototype.constructor = Person啦
Student.prototype.doing = function(){
   console.log("I am studying");
};

var s = new Student('hunger',2,'boy')
#继承过后的a既是Student的对象 也是Person的对象
s instanceof Student//true
//s._proto_ ===Student.prototype
s instanceof Person //true
//s._proto_._proto_ === Person.prototype

另一种方法,把方法的继承封装成函数inherit

function inherit(superType, subType){
    var _prototype  = Object.create(superType.prototype);
    _prototype.constructor = subType;
    subType.prototype = _prototype;
}
#使用方法
function Person(name, sex){
    this.name = name;
    this.sex = sex;
}

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

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

// 在继承函数之后写自己的方法,否则会被覆盖
Male.prototype.printAge = function(){
    console.log(this.age);
};

var m = new Male('Byron', 'm', 26);
m.printName();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容