DirtyMind
DirtyMind

Reputation: 2591

Not able to write Prototype function as Function Declarations in javascript. Why?

Why can not we write prototype function like function declaration:

only it is allowed in function expression:

       function SinglyLinkedList() {
         this.head = null;
         this.tail = null;
       }
  
        SinglyLinkedList.prototype.add = function(data){
        	console.log(data);
        } // working as expected

        function SinglyLinkedList.prototype.add(data){
        	console.log(data);
        }
        // showing error.

Upvotes: 0

Views: 48

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1075925

Because that's just not how the syntax is designed. Maybe it could have been designed that way, but it wasn't. The name (more precisely, binding identifier) in a function declaration must match the definition of an Identifier, which means it cannot be a property path like SinglyLinkedList.prototype.add.

Note that if you're looking for something shorter, you could use Object.assign (new, but polyfillable) and an object initializer using method syntax (new as of ES2015):

Object.assign(SinglyLinkedList.prototype, {
    add(data) {
        console.log(data);
    },
    remove(/*...*/) {
        // ...
    }
    // etc.
});

Or for pre-ES2015 environments (with a polyfill for Object.assign), property syntax rather than method syntax:

Object.assign(SinglyLinkedList.prototype, {
    add: function(data) {
        console.log(data);
    },
    remove: function(/*...*/) {
        // ...
    }
    // etc.
});

And of course, ES2015+ has class which is also more concise than the old way.

Upvotes: 2

deceze
deceze

Reputation: 522636

After the function keyword, you're allowed to write a function name. The function name must conform to valid naming conventions. . is invalid in a function name, making the syntax invalid.

The function keyword was simply not designed to create a function on a nested object. Its only job is to create a function, it's not concerned with where you put it afterwards.

Upvotes: 2

Chirag Ravindra
Chirag Ravindra

Reputation: 4830

The second method is not syntactically valid in JS

One possible way to assign a named function to a prototype:

function add(data) {
    ...
}

SinglyLinkedList.prototype.add = add;

Upvotes: -1

Related Questions