javascript,在名为attrName的函数中使用this.attrName

javascript,在名为attrName的函数中使用this.attrName,javascript,this,Javascript,This,我发现了一些奇怪的东西 function Man(){ this.Man = "Peter"; } 在我叫它之后。(不要将其用作构造函数) 我想会有结果的 alert(Man.Man)//-->Peter 但是。。我错了,实际上结果是: alert(Man.Man)//-->undefined alert(Man)//-->Peter 这真是令人困惑,它是怎么发生的???我会向你解释那里发生了什么 1. Man()函数中的this是窗口 2. 您正在调用该函数。它

我发现了一些奇怪的东西

function Man(){
    this.Man = "Peter";
}
在我叫它之后。(不要将其用作构造函数)

我想会有结果的

alert(Man.Man)//-->Peter
但是。。我错了,实际上结果是:

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

这真是令人困惑,它是怎么发生的???

我会向你解释那里发生了什么

1.
Man()
函数中的
this
窗口

2. 您正在调用该函数。它将全局变量
Man
的值设置为
“Peter”

请注意,
this.Man=“Peter”
等于
window.Man=“Peter”
as
指的是
窗口

3. 函数调用
Man()
Man
从函数变为字符串变量。现在
Man
是一个值为字符串的变量,它不包含属性
Man
,因此它是
未定义的

4.
现在,您实际上正在警告在
Man()
调用中创建的全局变量,它被设置为
“Peter”

的值。我使用了chrome控制台,并有一些其他发现

function Man(){
    this.Man = "Peter";
    console.log("this", this);
}
上面是指窗口。如果调用函数
Man()。您的行
Man.Man
应该在chrome中返回
undefined
。如果您使用
Man()。你可以写

function Man(){
    this.Man = "Peter";
    return this.Man;
}
这将返回值
Peter
。如果你想拥有一个属性
Man
,你可以使用write

如果有什么不清楚的地方,请寻求更多的帮助

更新为对评论的回应 您可以在不使用prototype的情况下使用构造函数(请参阅或使用以下语法:

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

要理解
这个
指的是什么,你可以看一看。在示例框中
这个
指的是“底层类函数”的新实例(对象)。在
函数Man(){this.Man=“Peter”}
这个
指的是这个.window。你可以阅读更多。

警报(Man)//-->Peter
?你确定吗?当你
警报
->
警报(人)
-它应该返回洞函数而不仅仅是它的属性。检查
这个
实际上指的是什么。是的…我在chrome控制台中尝试过它==这个引用窗口..当调用一个函数以获得帮助时;)@joey你把我弄糊涂了--。。我认为当使用函数Man作为构造函数时,我不必定义
Man.prototype={constructor:this.Man}
explicit,它指的是什么?我还有一个问题,当我们定义一个
函数
时,有
函数.prototype
的隐式定义,还有
函数.prototype.constructor==函数
我说得对吗?你说得对-见我上面的更新。关于原型,构造器和这一点,我将试图找到一个很好的解释。
alert(Man.Man)
alert(Man)
function Man(){
    this.Man = "Peter";
    console.log("this", this);
}
function Man(){
    this.Man = "Peter";
    return this.Man;
}
// 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; 
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