vuvu
vuvu

Reputation: 5338

JS - call a parent function

I found this JS code structure and I' wondering how to call the function move() from inside the function load:

JS

function Start(data) {

    this.move= function() {
      ....
    };

    function load(){
       // call move
    }

}

Upvotes: 1

Views: 97

Answers (5)

Alex K.
Alex K.

Reputation: 175826

function Start(data) {
    this.move = function() {
       ....
    };

    function load(obj) {
      obj.move();
    }

    load(this);
}

Upvotes: 2

Oday Fraiwan
Oday Fraiwan

Reputation: 1157

By using closures, that can be acheived by stroing the parent reference;

function Start(data) {
    var me = this;

    this.move= function() {
      ....
    };

    function load(){
       me.move();// call move
    }

}

Good Luck.

Upvotes: 1

Oleksandr T.
Oleksandr T.

Reputation: 77482

function Start(data) {
    var _this = this;

    this.move = function() {
      console.log('mode');
    }

    function load() {
       _this.move();
    }

    // load();
}

Start();
new Start(); 

Upvotes: 4

Rob Hardy
Rob Hardy

Reputation: 1821

The function Start() has to be instantiated as an object. So you would use:

function Start(data) {

  this.move = function() {
  ....
  };

  this.load = function(){
   // call move
    this.move();
  }
}

var s = new Start(foobar);
s.load();

Upvotes: 1

CSharper
CSharper

Reputation: 5580

This is a javascript closure. I've found this site to be helpful.

 var move = function () {
            alert("move");
        };

        load();
        function load() {
            move();
        }

This code will alert Move only once.

Upvotes: 1

Related Questions