在javascript中访问私有方法

时间:2014-05-13 14:24:36

标签: javascript private-methods

以下是我用于访问私有方法的javascript代码。但它没有用。我收到了TypeError: string is not a function条消息。有人可以帮帮我吗?

这是我的代码:

function Boy(firstName,lastName) {
    this.fisrtName = firstName;
    this.lastName = lastName ;
    var ladyLove = "Angelina";

    var returnLove = function() {
        return ladyLove;
    };

    this.sayLoud = function(){
        return returnLove();
    };
}

var achilles = new Boy("Bradley","Pitt");
var sayNow = achilles.sayLoud();
console.log(sayNow());

3 个答案:

答案 0 :(得分:3)

sayLoud()返回Angelina - 这是String,而不是function

你可能只想去:

console.log(sayNow);

答案 1 :(得分:2)

您应该使用console.log(sayNow);

,而不是将字符串用作函数

说明:

var achilles = new Boy("Bradley","Pitt"); // Will create a new object
var sayNow = achilles.sayLoud(); // call sayLoud(), return string
console.log(sayNow); // output the string

答案 2 :(得分:0)

试试这个

var achilles = new Boy("Bradley","Pitt");
var sayNow = achilles.sayLoud; 
console.log(sayNow());