سؤال

The following is my javascript code for accessing a private method. But it is not working. I receive a TypeError: string is not a function message. 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.

You probably just want to go for:

console.log(sayNow);

نصائح أخرى

Instead of using a string as a function, you should use 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 مع الإسناد
لا تنتمي إلى StackOverflow
scroll top