blue cat
blue cat

Reputation: 193

How to pass a string into the object method in Javascript?

I have an object method a like below:

var f = {
   a: function(e){
       e.call();
       console.log(t);    // Here should print “Hello world”
   }
};
f.a(function(){
    f.a.t = "Hello world";
    // How to pass the string “Hello world” into the object method “a” ?
});

e is an anonymous function. I call the e and now I want to pass a string Hello world into the object method a. If it's not allowed to use global variable, how can I pass the string into the object method?

Upvotes: 0

Views: 77

Answers (6)

Thakur Rock
Thakur Rock

Reputation: 565

f is java script object and you can add property to that.I just added f.t="Hello world".you can use f.t anywhere in programme wherever you have f scope.

var f = {
       a: function(e){
           e.call();
           console.log(f.t);    // Here should print “Hello world”
       }
    };
    f.a(function(){
        f.t = "Hello world";
        // How to pass the string “Hello world” into the object method “a” ?
    });

Upvotes: 0

Bakhtiiar Muzakparov
Bakhtiiar Muzakparov

Reputation: 2438

You may want to consider to change the return value of your eas below:

    var f = {
       a: function(e){
           var t = e.call();//here declare variable t
           console.log(t);    // Here should print “Hello world”
       }
    };
    f.a(function(){
        return "Hello world";//directly return string value from anonymous function
        // How to pass the string “Hello world” into the object method “a” ?
    });

Upvotes: 1

t.niese
t.niese

Reputation: 40842

If you want to call e in the context of f then you would need to pass f to call, writing e.call() would be equal to e().

Beside that t refers to a variable and not to the property t of a. You cannot set a variable that way, but you could store it in the object f

You would write it that way.

var f = {
   a: function(e){
       e.call(this);
       console.log(this.t);
   }
};
f.a(function(){
    this.t = "Hello world";
});

Upvotes: 0

Vivek Athalye
Vivek Athalye

Reputation: 2979

Why not define a property in object like:

var f = {
  t: '',
  a: function(e){
    e.call();
    console.log(this.t);    // Here should print “Hello world”
  }
};
f.a(function(){
    f.t = "Hello world";
});

Upvotes: 0

jotaelesalinas
jotaelesalinas

Reputation: 1497

What is t's scope? If it's an attribute of f, write this:

var f = {
    a: function(e){
        e.call();
        console.log(this.t); // this line changed
    }
};
f.a(function(){
    f.t = "Hello world"; // this line changed
});

Upvotes: 0

sumit chauhan
sumit chauhan

Reputation: 1300

See below snippet

var f = {
   a: function(e){
       e.call();
       console.log(f.a.t);    // Here should print “Hello world”
   }
};
f.a(function(){
    f.a.t = "Hello world";
    // How to pass the string “Hello world” into the object method “a” ?
});

Upvotes: 0

Related Questions