您好,我是一名前端小萌新,最近看到以下代码非常不理解。。。
为啥changeName()里的那个this和person()里的this,指的都是person对象呢?我看W3C文档里讲this指的应该是它本身这个函数对象呀(即指changeName),不理解啊。。。求路过的大神点拨一下,不胜感激!
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.changeName=changeName;
function changeName(name)
{
this.lastname=name;
}
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
当作构造函数调用时,this 指向了这个构造函数调用时候实例化出来的对象;
当然,构造函数其实也是一个函数,如果把它当作一个普通函数执行,这个 this 仍然执行全局:
看你是如何调用的,this的指向问题有很多文章都讲了,网上很多这样的文章,有兴趣可以去搜索一下。
给你两篇博客看吧
this,记住就好了,语法规定,没有为什么。http://zonxin.github.io/post/...
原型链,难度提升有点儿大,要仔细多读几遍
http://zonxin.github.io/post/...