简体   繁体   English

在javascript中访问私有方法

[英]Accessing a private method in javascript

The following is my javascript code for accessing a private method. 以下是我的用于访问私有方法的JavaScript代码。 But it is not working. 但这是行不通的。 I receive a TypeError: string is not a function message. 我收到TypeError: string is not a function消息。 Can anyone please help me? 谁能帮帮我吗?

Here is my code: 这是我的代码:

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

sayLoud() returns Angelina - which is a String , not a function . sayLoud()返回Angelina这是一个String而不是一个function

You probably just want to go for: 您可能只想去:

console.log(sayNow);

Instead of using a string as a function, you should use console.log(sayNow); 不要使用字符串作为函数,而应使用console.log(sayNow);

Explained: 解释:

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

try this 尝试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM