-1

So I have a Javascript function i.e

var object = function(){
    function sayHello(){
       console.log("Hello");
    } 
}

Is there a way to redefine the object.sayHello method later on in my code such that instead it prints "Bonjour"?

  • Did you mean `function Object() { ... }; var object = new Object();`? – le_m Jun 08 '17 at 18:31
  • No, object is defined as a function. Later on I do initialize a var newObj = new object. I think the two function the same though. – absoloo Jun 08 '17 at 18:32
  • Here: https://jsfiddle.net/khrismuc/r490an2h/ edit: your code doesn't create `object.sayHello` –  Jun 08 '17 at 18:34
  • I appreciate the help, but what you made was an object, object needs to be a function in my case. – absoloo Jun 08 '17 at 18:36
  • You are right, I really only need to be able to call sayHello() inside of object, but I want to modify it elsewhere, does that makes sense? – absoloo Jun 08 '17 at 18:37
  • In that case you need to do this: https://jsfiddle.net/khrismuc/r490an2h/1/ (a function doesn't have methods, afaik) –  Jun 08 '17 at 18:37
  • So I need to do just that but before I create a new object for "object". I want to modify the function as a whole, and not just an instance of the function. – absoloo Jun 08 '17 at 18:40
  • Read this Q&A: https://stackoverflow.com/a/7694583/1161948 – ThisClark Jun 08 '17 at 19:39
  • Thank you for the help, I finally figured it out. I just needed to make var object = function(){ function sayHello(){ sayHi(); } } and then define sayHi() outside of 'object' so whenever I wanted to change the functionality of sayHello(), I just override sayHi(). Also this implementation allows you to use the privileged methods of sayHello() if you also pass 'self' to sayHi(). – absoloo Jun 09 '17 at 17:53

2 Answers2

0

You can override functions in Javascript. All you have to do is re-declare it later on.

var hello = function(){
    alert("Hello");
}

function changeFunction(){
    hello = function(){
     alert("Goodbye");
    }
}
<button onclick="hello()">Run Function</button>
<button onclick="changeFunction()">Change function</button>
  • Which function? Hello() is a global variable, you can change it from any location, inside any other function you want. – Tyler Gaffaney Jun 08 '17 at 18:47
  • So Hello() has another function inside of it, sayHello(), look at the original code sample I posted, and I want to only change the sayHello() function inside of Hello() without redeclaring the entire function. Does that make sense? – absoloo Jun 08 '17 at 18:49
  • Yes, there is no way to reference only the nested function. – Tyler Gaffaney Jun 08 '17 at 18:51
0

js

var input = document.getElementById('input').value;
var object = function(){
    function sayHello(input){
       console.log(input);
    } 
}

and html

<input type="text" name="input" id="input" placeholder="enter greetings">
Oleg Markoff
  • 321
  • 2
  • 7