ITeye博客

javaScript 之this的使用

laj12347 · 2013-01-04 21:20 · Web前端 · Markdown

1、this的使用及其代表的对象


<script text="javascript">
	function Person(name,age,job){
		this.name = name;
		this.age = age;
		this.job = job;
	}
	Person.sayName= function(){ 
		alert(this.name);
	};
	var tanya = new Person("tanya","30","female");
	var ansel = new Person("ansel","30","male");
	tanya.sayName();
	ansel.sayName();
</script>

在sayName方法中的this代表 Person对象。在这段代码中,this代表调用sayName方法的对象。 2、通过this实现继承,


<script text="javascript">
	function Parent(username){
		this.username=username;
		this.sayHello=function()
		{
			alert(this.username)	
		}
	}

	function Child(username,password){
		
		this.method=Parent;
		this.method(username);
		delete this.method;
		this.password=password;           
	}
</script>

在上面的这段代码中,this.method=Parent; 把Parent 当做方法调用,thid.method(username)调用方法的时候,Parent中的this代表Child对象,这样就是实现了把Parent中的方法和属性传递给Child对象。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。