overloading vs overriding in javascript

In a recent JavaScript interview I was asked about overloading vs overriding. I know this is a concept in Java:

https://softwareengineering.stackexchange.com/questions/164353/whats-the-difference-between-overloading-a-method-and-overriding-it-in-java

But is there something similar in JavaScript, and if so what would be code examples? My understanding is that overloading isn't common in javascript. Why would you need to use "overloading" in JS?

OverRiding is a bit clearer to me - an example of over riding would be in subclassing where you are inheriting from a super class but over riding some methods/properties to create unique ones for a sub class.


JavaScript does not support overloading.

JavaScript supports overriding, so if you define two functions with the same name, the last one defined will override the previously defined version and every time a call will be made to the function, the last defined one will get executed.

more read here http://blog.mastykarz.nl/overloading-functions-javascript/


There's a nice example of 'faking' JavaScript function overloading here: https://stackoverflow.com/a/457589/2754135

You basically use a parameter in your function that takes an object, that object contains any number of parameters you want.

It's not actually overloading obviously, cause that's not possible in JavaScript.


there is no need for the traditional concept of overload in javascript, because of its dynamic nature. In the more traditional programming languages, as Java, you can define a method multiple times with different signatures and the language will correctly use the method you want to call just using the signature: thats called overload of methods. On the other hand override is the possibility to redefine a method of the parent class in the child class. To do overload in javascript it is common practice to use last parameter that is called options. For example

function yourFunction(firstParam, secondParam, options) {};

the options is just a javascript object that have props you want to pass. Then you can use the so called "options" pattern to check for props. To do override it is more difficult in pure javascript because of the prototypal nature of the language: when you "extend" a base object with a new one, you can use .call() function of the constructor object passing this to decorate the newly created object with the parent props.

链接地址: http://www.djcxy.com/p/51988.html

上一篇: 经典的asp JScript中的重载函数

下一篇: 重载与重写在JavaScript中