Ruby Jacob
Ruby Jacob

Reputation: 21

How to source code in this

var a = ["one", "two", "three"];
 console.log(a.indexOf("two")); // output = 1

 a.indexOf = function(val) {
  return 'HAHAHA';
};

console.log(a.indexOf("two")); // output = 'HAHAHA'

What are some ways to restore the functionality of indexOf?

console.log(a.indexOf("two")); // output = 1

Upvotes: 0

Views: 25

Answers (1)

Sébastien
Sébastien

Reputation: 12139

You simply re-assign the original function which comes from Array.prototype.

var a = ["one", "two", "three"];
 console.log(a.indexOf("two")); // output = 1

a.indexOf = function(val) {
  return 'HAHAHA';
};

console.log(a.indexOf("two")); // output = 'HAHAHA'

a.indexOf = Array.prototype.indexOf; // re-assign the original function
                                     // which is inherited from Array.prototype.

console.log(a.indexOf("two")); // output = 1

Upvotes: 1

Related Questions