javascript 中this 详解 1

在javascript 中this 的定义:包含它的函数被调用时,所属的对象。

这句话非常简练精准!

1. 首先this是一个对象!

2. 其次,this的值是变化的,包含它的函数被调用时所属的对象,随着该函数被不同的对象调用,this也就不同了。

请看以下例子:

例子a:

function init(){
console.log('this is windows init!');
}
function test(){
var init=function(){console.log('this is test init!');};
this.init();
}

test();
输出:this is windows init!


大家可以看到,我在window中直接调用了test函数,所以test函数此时属于window对象,this=window!那么this.init就是在window中直接定义的 function init 了;所以输出的是' this is windows init ! '


例子b:

function init(){
console.log('this is windows init!');
}
function test(){
var init=function(){console.log('this is test init!');};
this.init();
}
test.prototype={init:function(){console.log('this is test prototype init!')}};

new test();

输出:this is test prototype init!

在例子b中,我用的new test()进行test调用,那么这次呢?这句话的意思是新建一个 test函数对象并且执行它,显然是test 的原型也就是test本身调用了(执行了)自己,此

时,test函数中的this就是test的本身或者说是他的原型,那么 this.init = test.prototype.init 了,也就是输出了 ’ this is test prototype init! ‘ .

好了,今天就理解了这么多,下次接着学习!

路漫漫啊!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值