在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ javascript中this的指向的疑惑

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是一個(gè)對(duì)象,對(duì)象的this應(yīng)該指向?qū)ο蟊旧?,也就是prototype,經(jīng)過測(cè)試,它不指向a.prototype,也不指向a,而指向b。

回答
編輯回答
葬憶

this的綁定取決于調(diào)用的模式,JavaScript 中一共有4種調(diào)用模式:

  • 函數(shù)調(diào)用模式
  • 構(gòu)造器調(diào)用模式
  • apply/call 調(diào)用模式
  • 方法調(diào)用模式
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()              // 函數(shù)調(diào)用模式,this綁定到全局對(duì)象

var b = new a(); // 構(gòu)造器調(diào)用模式, 通過new 來(lái)調(diào)用, this 會(huì)被綁定到新對(duì)象上,即 b
b.testThis(); //所以 此時(shí) this指向 b 

a.prototype.testThis.call(a);// apply/call 調(diào)用模式, apply 方法接收的第一個(gè)參數(shù)就是要綁定給this的值。

a.prototype.testThis();// 方法調(diào)用模式,綁定發(fā)生在調(diào)用的時(shí)候,延遲綁定,此時(shí) this指向a.prototype

上面都是從《JavaScript 語(yǔ)言精粹》里面函數(shù)一章可以找到

2018年6月8日 18:19
編輯回答
耍太極

this是運(yùn)行時(shí)確定,而不是在函數(shù)聲明時(shí)。
this指向函數(shù)的調(diào)用者同步需要記住this是不會(huì)沿著原型鏈向下找

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(); //此時(shí) this指向 b 

a.prototype.testThis.call(a);//此時(shí) this指向 a

a.prototype.testThis();//此時(shí) this指向a.prototype
2018年7月12日 11:04
編輯回答
朕略萌

首先,new的時(shí)候,會(huì)將b的_proto_指向a的prototype,類似一個(gè)繼承的過程(所以b.constructor==a)

其次,this關(guān)鍵字是在執(zhí)行時(shí)才有指向的東西,取決于執(zhí)行到那一行的時(shí)候,執(zhí)行對(duì)象是誰(shuí)

最后,b.testThis(),進(jìn)入方法塊兒后,this應(yīng)當(dāng)指向執(zhí)行對(duì)象,b調(diào)用的該方法,this只能指向b,而不會(huì)指向其他的。a是b的構(gòu)造方法,a.prototype是a的原型對(duì)象,只有b._proto_跟a.prototype有關(guān)系。

2018年4月27日 11:01
編輯回答
淡墨
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沒關(guān)系了

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

var b = {
    name: "b",
    testThis: a.testThis
};
a.testThis();//"a"
b.testThis();//"b"
2017年6月5日 04:32