<!DOCTYPE html>
<html>
<body>
<script>
function person(firstname, lastname, age, eyecolor) {
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
this.eyecolor = eyecolor;
}
myFather = new person("Bill", "Gates", 56, "blue");
document.write(myFather.firstname + " is " + myFather.age + " years old.");
</script>
</body>
</html>
之前的在另一个问题的回答 http://.com/q/1010000000620780#a-1020000000621247
this:
1.指向全局,浏览器中指向window
2.对象实例方法中this指向对象本身,如:
var a = {b : 1, bar : function(){alert(this.b) // this 与 a 相同}};
3.构造函数this指向未来的实例,如同楼主的例子:
var p = new person(/**/); // 此时this指向p
this不是定义时指定,而是运行时指定
基本只有 @jacklau 的答案答到了点上,其它的要么卖萌,要么自己没理解,要么无法说出来让别人理解。
自己不知道不要紧,最怕自己知道的是错的,更怕的是把错误的东西再教给别人,这是我看到这个答案之后感到很害怕的地方,因此也特意写一下。
首先,this
是一个语言中的关键字,这里我们假设不懂英语,不知道它的中文意思是当前、这个之类的,它就是一个对象。
this
这个对象是谁取决于函数被调用的方式。在JavaScript中,函数有四种调用方式:
- 直接调用,如
func()
,此时函数中的this
在ES3/ES5非严格模式下为全局对象,在浏览器中即为window
- 作为方法调用,如
obj.func()
,此时函数中的this
为obj
-
apply
/call
调用,如obj1.func.apply(obj2)
,此时函数中的this
为apply
/call
的第一个参数,如前例中为obj2
- 作为构造函数(
constructor
)调用,如new func()
,这种情况下this
为一个新的对象,假设叫它为obj
,默认情况(func()
没有使用return
显式返回对象的情况下)下obj
会作为new func()
的结果被返回
你的例子即这里说的第四种情况,person()
是作为一个构造函数被调用的,此时相当于:
function(一堆参数){
var obj={}; //这句是想象的
obj.xx = xx; //对this的一堆赋值
return obj; //这句是想象的
}
所以看这句
myFather = new person("Bill", "Gates", 56, "blue");
相当于在person()
被调用时新建了一个对象,然后分别对对象的各属性赋值,最后返回这个新对象,也就是这些赋值最后给了myFather
。
这正是其它语言中“类”和“实例”的关系。如要详细了解可以读一些JavaScript面向对象实现的方案,当然前提是了解“面向对象”的概念。
推荐《JavaScript语言精粹》,很薄,但是这些基础知识都比较全面地覆盖到了。
题主为何辣么萌
this就是本身对象
指向自己。function person(firstname,lastname,age,eyecolor) {
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
this.eyecolor = eyecolor;
}
这里的this就指向了person.
this.firstname = firstname相当于person.firstname = firstname.
this指向对象本身,类似于python中的self
你有学过其他编程语言么?this关键字的意思就是对当前对象的引用。js的function就是对象。例如你这个person对象,它有自己的姓,有自己的名,自己的年纪,自己眼睛的颜色。this表达的意思就是“自己的”.this.age==自己的年纪。明白了吗?
JS中关于this最简单直接的解释就是谁调用它,谁就是this