Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The inheritance of javascript

Maybe this question is easy,but I can't understand now.

String.prototype.self=function()
{
    return this;
}
var s="s";

alert("s".self()=="s".self()) //false;
alert(s.self()==s.self()) //false;

If you know the reason, please tell me why the result is "false".

like image 825
user302376 Avatar asked Jul 14 '10 03:07

user302376


People also ask

What are the types of inheritance in JavaScript?

Mainly there are three types of inheritance in JavaScript. They are, prototypal, pseudo classical, and functional.

Does JavaScript follow inheritance?

JavaScript doesn't use classical inheritance. Instead, it uses prototypal inheritance. In prototypal inheritance, an object “inherits” properties from another object via the prototype linkage.

What is inheritance in JavaScript ES6?

The ES6 JavaScript supports Object-Oriented programming components such as Object, Class and Methods. Further in Classes we can implement inheritance to make child inherits all methods of Parent Class. This can be done using the extends and super keywords. We use the extends keyword to implement the inheritance in ES6.

How do you handle inheritance in JavaScript?

By calling the super() method in the constructor method, we call the parent's constructor method and gets access to the parent's properties and methods. Inheritance is useful for code reusability: reuse properties and methods of an existing class when you create a new class.


1 Answers

That's because when a property is accessed from a primitive value, such as "s", the property accesors coerce it internally ToObject, and the comparison fails because it checks two different object references.

For example:

String.prototype.test = function() {
  return typeof this;
}

"s".test(); // "object"

It's like comparing:

new String("s") == new String("s"); // false
like image 123
Christian C. Salvadó Avatar answered Sep 20 '22 10:09

Christian C. Salvadó