troubleshooting Question

"this" on javascript

Avatar of rwniceing
rwniceing asked on
JavaScriptjQueryWeb Browsers
24 Comments2 Solutions496 ViewsLast Modified:
Dear Experts

Question-1
<script type="text/javascript">console.log(this)</script>
that will show "this" as window object such as window{top:window,window:Window,,Location.......}

<script type="text/javascript"> 
funtcion v1(){
this.space="v1";
console.log(this);
}
funtcion v2(){
this.space="v2";
console.log(this);
}
v1();
V2();
</script>

that function code are same  to show this as window object . So I believe "this"  is public object of window. But when I show "this" by  b with new such as follows, it will show v1{} for this and this.space is equal to v2 instead of v1, so this key is not public  after b=new v1() ?
v1(); //window{}
v2();//window{}
var b= new v1();  //v1{}
console.log(this.space) //v2  instead of v1, why ?

question-2
<a href="#" onclick="javascript:alert(this.innerHTML)>Testing</a>
this keyword  in anchor tag  is referring to achor object  but not window object, why ?
it is different this keyword in html and javascript area by ECMA script spec, where  can prove or show it ?



Please advise and read the following code attached

Rwniceing

<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head>
<title>this</title>
<script type="text/javascript">

function v1(id){
this.space="v1";
console.log("1-" ,this);
}
function v2(id){
this.space="v2";
console.log("2-" ,this);
}

//--------------------------
function start(id){
v1();  //1- window{}
v2();  //2- window{}
console.log("3-", this.space);  //3- v2
var b= new v1();  //1- v1{space:"v1"}
console.log("4-", this.space);//4- v2
console.log("5-", b.space);//5- v1

}

</script>
<body onload="start();">
<div>this, window object</div>
<a href="#" style="color:blue" onclick="javascript:aert(this.innerHTML);>Testing</a>
<div id="wrapper">Warpper</div>
</body>
</html>
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 2 Answers and 24 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 24 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros