Javascript构造函数中的私有函数无法公开访问

时间:2014-09-09 16:37:47

标签: javascript object

我有这个人对象

function person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;

    function sayName(){
        var full="";    
        full="Hello my name is "+this.firstName + " "+this.lastName;
    }
}

并制作了这个对象的实例

var raul = new person("Raul","Zamora","19","brown")

我无法弄清楚为什么函数sayName不起作用。我正在实施它:

document.getElementById("sayName").innerHTML=raul.sayName();

其中sayName已被定义为HTML部分的ID。

3 个答案:

答案 0 :(得分:2)

它不起作用,因为sayName函数仅在构造函数的范围内可见(因此完全没用)。

要在实例上使用该功能,请使用

person.prototype.sayName = function(){
   var full="Hello my name is "+this.firstName + " "+this.lastName;
   return full; // don't forget to return the string
}

有关详情,请参阅MDN的这篇文章:Introduction to Object-Oriented JavaScript

答案 1 :(得分:0)

您的功能sayName不属于您的班级,为此,您需要使用this或使用propotype

来声明它

使用this

function person(first, last, age, eye) {
            this.sayName = function(){
                return "Hello my name is "+this.firstName + " "+this.lastName;
            }
        }

使用prototype

person.prototype.sayName = function(){
     return "Hello my name is "+this.firstName + " "+this.lastName;
}

另外sayName没有返回任何内容。

答案 2 :(得分:0)

你在那里有一个本地函数声明。通过赋值使其成为对象的属性 - 就像您编写this.firstName = first not var firstName = first一样。

这将使它成为一种可从外部访问的方法:

function person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;

    this.sayName = function sayName(){
        var full="Hello my name is "+this.firstName + " "+this.lastName;
    };
}

然而,有些反对意见:

  • 构造函数名称应大写
  • 您的sayName方法需要return字符串,否则您的示例调用将无法正常工作
  • 将原型用于可在实例(例如方法)is preferable
  • 之间共享的值

所以我们到了

function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}
Person.prototype.sayName = function sayName(){
    return "Hello my name is "+this.firstName + " "+this.lastName;
};
var raul = new Person("Raul","Zamora","19","brown");
document.getElementById("sayName").textContent = raul.sayName();