Call a method in different page: JavaScript

Hi,
I have a method in common property, and I want to use it in a home page property, but I don’t want to re-create the method?
I tried with a test method and is return test is not a function:

var MySite = {
  // All pages
  'common': {
  init: function() {

    var test = function(i) {
      return i;
    }
    test();
  },
  // Home page
  'home': {
    init: function() {
      console.table(MySite.common.init.test('call'));
    },
  }
}


      console.table(SmileCare.common.init.test('ddd'));

You have a scope problem - you can’t access test because it’s a local variable inside your MySite.common.init() function.

It’s hard to know exactly what you’re trying to do without more information but you could always add your test function to the common object. For example:

var MySite = {
  // All pages
  'common': {
    init: function() {
      console.log(MySite.common.test('common init...'));
    },
    test: function(i) {
      return i;
    }
  },
  
  // Home page
  'home': {
    init: function() {
      console.log(MySite.common.test('home call'));
    },
  }
}

MySite.common.init();
MySite.home.init();
console.log(MySite.common.test('hello'));

Does that help?

1 Like

It helps a lot, thanks :slight_smile:
Your rock!

1 Like

De rien, je suis content que cela ait été utile :slight_smile:

If you want to push your JS skills, check out https://javascript30.com/ - I plan to do it when I have more time…

Comment tu sais que je suis français?
Je suis en train d’apprendre React, je vais suivre cette formation, c’est frustrant parce que je pensait être bon avec js.
D’ailleurs j’ai obtenu le frontend certificate, FCC et c’est pas facile a obtenir

C’est parce que j’ai vu la mention de pétanque dans ta bio :wink:

J’ai grandi en Australie mais en ce moment j’habite à Paris. J’apprends encore le français…

Je ne connais pas FCC, mais ça a l’air très bien. Nous n’arrêtons jamais d’apprendre (j’ai commencé en 1997 avec HTML…)

Bon courage !

1 Like