javascript:这段代码需要解释
谁能向我解释此代码(提示javascript:这段代码需要解释,javascript,class,methods,this,self,Javascript,Class,Methods,This,Self,谁能向我解释此代码(提示“嗨!我的名字是马克”出现): 为什么我没有看到alert if返回{person:person}是否已删除?什么person:person在这里 另外,为什么在函数person(){}中未定义this.name(而不是self.name)?主要问题是不应返回{person:person},但不应指定返回或“return this;” newperson(“Mark”)将创建Person的实例,但函数Person返回{Person:Person}。在{person:per
“嗨!我的名字是马克”
出现):
为什么我没有看到alert if返回{person:person}代码>是否已删除?什么person:person
在这里
另外,为什么在函数person(){}
中未定义this.name
(而不是self.name)?主要问题是不应返回{person:person},但不应指定返回或“return this;”
newperson(“Mark”)将创建Person的实例,但函数Person返回{Person:Person}。在{person:person}内部,正确的一个(值)是方法。
var x=newperson(“Mark”)将返回{Person:function Person(){alert(“Hi…”)}。
x、 person()将显示警报。此代码非常棘手:
function Person(name) {
//'P' makes us think about this function as a constructor
var self = this;
// Closure, when the person function is executed
//"this" is not a Person, is another object, but "self" will be accesible
// by the function person
this.name = name;
// this is an internal function, it does not exist out of Person
function person(){
alert("Hi! My name is "+self.name);
}
return {person:person};
//This should not be here if the Person function were a proper constructor,
//it returns an object which only attribute is the function person
}
new Person("Mark").person();
// as Person returns an object (not a Person object) with the person attribute,
// you can call that attribute
与此等效但更清晰的代码是:
var p={
person: function () {
var self={name: "Mark"};
(function(){
alert("Hi! My name is "+ self.name);
})();
}
};
p.person();
Niels的回答是正确的,为了回答您的其余问题,this.name在子函数中不起作用,因为name属于父函数,所以您必须声明该父作用域的实例(在您的示例中为self)无法访问父级的属性。抱歉,您的代码不是等效代码,因为它不显示带有名称的警报,名称未定义。您的代码在这里:谢谢。
var p={
person: function () {
var self={name: "Mark"};
(function(){
alert("Hi! My name is "+ self.name);
})();
}
};
p.person();