문제

I found something strange..

function Man(){
    this.Man = "Peter";
}

after I call it. (not use it as a constructor)

Man()

I think a result will be

alert(Man.Man)//-->Peter

but.. I'm wrong , actually the result is :

alert(Man.Man)//-->undefined
alert(Man)//-->Peter

That was really confusing ,how it happened??

도움이 되었습니까?

해결책

I'll explain you what is happening there.

1

function Man(){
    this.Man = "Peter";
}

The this in Man() function is window.

2

Man();

You are calling the function. Which sets the global variable Man's value to "Peter".

Note that this.Man = "Peter" is equal to window.Man = "Peter" as this is referring to the window.

3

alert(Man.Man)

The function call Man(); in step 2 has made the Man from a function to a string variable. Now Man is a variable whose value is a string and it doesn't contain the property Man, so it is undefined.

4

alert(Man)

Now, you are actually alerting the global variable which was created in Man() call and it was set the value of "Peter"

다른 팁

I used the chrome console and had some other findings

function Man(){
    this.Man = "Peter";
    console.log("this", this);
}

Above this refers to Window. If you call the function Man() nothing is returned since the function does not return anything but sets the property Man on the window-object to be Peter. Your line Man.Man should return undefined in chrome. If you use Man().Man you will get undefined as well since this refers to the window object and the function Man() has no property Man. You could write

function Man(){
    this.Man = "Peter";
    return this.Man;
}

This returns the value Peter. If you want to have a property Man you could use a constructor function write

// set this.Man == window.Man to Peter    
function Man() { this.Man = "Peter"; } 

// create an constructor for each object Man
Man.prototype = { constructor: this.Man } 

// create an object 
var man = new Man(); 

// call his property which was set in the constructor of the prototype
man.Man; 

Please ask for more help if anything is unclear.

Update as response to the comment

You can use a constructor without using prototype (see examples at mdn or this question if you use this syntax:

function Box(color) // Constructor
{
    this.color = color;
}

var redBox = new Box("red");
var blueBox = new Box("blue");

redBox.color; // returns red
blueBox.color; // returns blue

To understand where this refers to you can take a look at understanding javascript this. In the box-example this refers to the new instance (object) of the "underlying class function". In function Man(){this.Man = "Peter"} the this refers to this.window. You can read more about protype in this book.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top