javascript中this的指向的疑惑

function a(){};

a.prototype.testThis = function() {
    console.log(a.prototype == this); // false
    console.log(a == this); // false
    console.log(b == this); // true
};

var b = new a();

b.testThis(); // 

按理说,prototype是一个对象,对象的this应该指向对象本身,也就是prototype,经过测试,它不指向a.prototype,也不指向a,而指向b。

阅读 1.9k
4 个回答

this的绑定取决于调用的模式,JavaScript 中一共有4种调用模式:

  • 函数调用模式
  • 构造器调用模式
  • apply/call 调用模式
  • 方法调用模式
function a(){
   console.log(this)
};

a.prototype.testThis = function() {
    console.log("a.prototype == this:"+(a.prototype == this)); // false
    console.log("a == this:"+(a == this)); // false
    console.log("b == this:"+(b == this)); // true
};

a()              // 函数调用模式,this绑定到全局对象

var b = new a(); // 构造器调用模式, 通过new 来调用, this 会被绑定到新对象上,即 b
b.testThis(); //所以 此时 this指向 b 

a.prototype.testThis.call(a);// apply/call 调用模式, apply 方法接收的第一个参数就是要绑定给this的值。

a.prototype.testThis();// 方法调用模式,绑定发生在调用的时候,延迟绑定,此时 this指向a.prototype

上面都是从《JavaScript 语言精粹》里面函数一章可以找到

this是运行时确定,而不是在函数声明时。
this指向函数的调用者同步需要记住this是不会沿着原型链向下找

function a(){};

a.prototype.testThis = function() {
    console.log("a.prototype == this:"+(a.prototype == this)); // false
    console.log("a == this:"+(a == this)); // false
    console.log("b == this:"+(b == this)); // true
};

var b = new a();

b.testThis(); //此时 this指向 b 

a.prototype.testThis.call(a);//此时 this指向 a

a.prototype.testThis();//此时 this指向a.prototype

首先,new的时候,会将b的_proto_指向a的prototype,类似一个继承的过程(所以b.constructor==a)

其次,this关键字是在执行时才有指向的东西,取决于执行到那一行的时候,执行对象是谁

最后,b.testThis(),进入方法块儿后,this应当指向执行对象,b调用的该方法,this只能指向b,而不会指向其他的。a是b的构造方法,a.prototype是a的原型对象,只有b._proto_跟a.prototype有关系。

function a(){};

a.prototype.testThis = function() {
    console.log(a.prototype == this); // false
    console.log(a == this); // false
    console.log(b == this); // true
};
//new过程
var b = {};
b.__proto__ = a.prototype;
a.call(b);

b.testThis(); // 

我是这样理解的
把操作交给b就跟a没关系了

var a = {
    name: "a",
    testThis: function () {
        console.log(this.name)
    }
}

var b = {
    name: "b",
    testThis: a.testThis
};
a.testThis();//"a"
b.testThis();//"b"
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题