javascript:这段代码需要解释

时间:2014-02-27 14:41:01

标签: javascript class methods this self

谁能解释我这段代码(警告"Hi! My name is Mark"出现):

function Person(name) {
    var self = this;
    this.name = name;

    function person(){
        alert("Hi! My name is "+self.name);
    }
    return {person:person};
}

new Person("Mark").person();

如果return {person:person};被移除,为什么我看不到警报? person:person在这里是什么?

另外,为什么在this.name中未定义function person(){}(非self.name)?

3 个答案:

答案 0 :(得分:1)

主要问题是你不应该返回{person:person},但你不应该指定一个回报或“返回这个”。

new Person(“Mark”)将创建Person的实例,但函数Person返回{person:person}。在{person:person}里面,正确的(值)是方法。 var x = new Person(“Mark”)将返回{person:function person(){alert(“Hi ...”)}。 x.person()将显示警告。

答案 1 :(得分:1)

这段代码非常棘手:

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();

答案 2 :(得分:1)

Niels的回答是正确的,为了回答你的其余问题,this.name在子函数中不起作用,因为name属于父函数,所以你必须声明那个父作用域的实例(在你的case self)能够访问父级的属性。