What is the alternative of "this" in javasctipt?

Hi,

I want to start coding with out the use of keyword “this”, can any one suggest how to do this for example here i am trying to develop a some helper functions and i do not know any alternative to this which will be supported …

I have not been able to understand the scope and meaning of this and was very happy to find the author of “The Good Parts Javascript” also suggest so , but he did not suggested what to do instead of “this” ?

Can any one please help here …I need to find alternative to this …Thanks

Note - Also if any one can suggest alternative of “new” keyword as well …


function Queue() {
    "use strict";
    var items = [];

    this.enqueue = function (element) {
        items.push(element);
    };

    this.dequeue = function () {
        return items.shift();
    };

    this.front = function () {
        return items[0];
    };

    this.isEmpty = function () {
        return items.length === 0;
    };

    this.size = function () {
        return items.length;
    };

    this.print = function () {
        console.log(items.toString());
    };
}
var Queue = function() {
  var items = [];
  
  var enqueue = function(element) {
    items.push(element);
  };
  var dequeue = function() {
    return items.shift();
  };
  var front = function() {
    return items[0];
  };
  var isEmpty = function() {
    return items.length === 0;
  }
  var size = function() {
    return items.length;
  }
  var print = function() {
    console.log(items.toString());
  }
  return {
    enqueue: enqueue,
    dequeue: dequeue,
    front: front,
    isEmpty: isEmpty,
    size: size,
    print: print
  };
};

var myQueue = Queue();
myQueue.size(); // yields 0
myQueue.enqueue('hello')
myQueue.enqueue('goodbye')
myQueue.size(); // yields 2
myQueue.print(); // yields hello,goodbye
3 Likes

@camperextraordinaire - thank you so much , so will this work in all versions and javascript libraries and the last block of return , i could not understand that below - can you please guide me here …


return {
    enqueue: enqueue,
    dequeue: dequeue,
    front: front,
    isEmpty: isEmpty,
    size: size,
    print: print
  };

@camperextraordinaire - thanks i got it now …

Great write up @camperextraordinaire! :clap::clap::clap:

or

return {enqueue, dequeue, front, isEmpty, size, print}

to refer to variables with same names as properties

there’s a laundry list of historical issues with this in javascript - but it works well and is necessary - as is new - when writing modern modular code with es6 classes and arrow functions

2 Likes

I’d suggest watching FunFunFunction’s amazing videos on Object Creation in JavaScript. Helps you fully understand how it works and shows you a bunch of ways of doing things.

1 Like