this易错点

本文解析了JavaScript中this关键字的行为变化及函数原型属性的作用原理。详细介绍了不同上下文中this的指向,包括普通函数调用、严格模式下及构造函数中的表现,并探讨了函数原型属性如何影响实例共享。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.如果不是用new调用,在函数里面使用this都是指代全局范围的this。

foo = "bar"; 
  function testThis() {
    this.foo = "foo";
  }
  console.log(this.foo); //logs "bar"
  testThis();
  console.log(this.foo); //logs "foo"

除非你使用严格模式,这时候this就会变成undefined。

foo = "bar";
  function testThis() {
    "use strict";
    this.foo = "foo";
  }
  console.log(this.foo); //logs "bar"
  testThis();  //Uncaught TypeError: Cannot set property 'foo' of undefined 

如果你在调用函数的时候在前面使用了new,this就会变成一个新的值,和global的this脱离干系。

 foo = "bar"; 
  function testThis() {
    this.foo = "foo";
  }
  console.log(this.foo); //logs "bar"
  new testThis();
  console.log(this.foo); //logs "bar"
  console.log(new testThis().foo); //logs "foo"

函数里面的this其实相对比较好理解,如果我们在一个函数里面使用this,需要注意的就是我们调用函数的方式,如果是正常的方式调用函数,this指代全局的this,如果我们加一个new,这个函数就变成了一个构造函数,我们就创建了一个实例,this指代这个实例,这个和其他面向对象的语言很像。

2.通过一个函数创建的实例会共享这个函数的prototype属性的值,如果你给这个函数的prototype赋值一个Array,那么所有的实例都会共享这个Array,除非你在实例里面重写了这个Array,这种情况下,函数的prototype的Array就会被隐藏掉。

function Thing() {
}
Thing.prototype.things = [];
var thing1 = new Thing();
var thing2 = new Thing();
thing1.things.push("foo");
console.log(thing2.things); //logs ["foo"]

给一个函数的prototype赋值一个Array通常是一个错误的做法。如果你想每一个实例有他们专属的Array,你应该在函数里面创建而不是在prototype里面创建。

function Thing() {
    this.things = [];
} 
 var thing1 = new Thing();
 var thing2 = new Thing();
thing1.things.push("foo");
console.log(thing1.things); //logs ["foo"]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值