Prototypal inheritance issue in javascript

I understand what prototype inheritance is, but I should be confused about the implementation. I thought that changing the prototype of the function constructor would affect all instances of this constructor, but it is not. How does JS search for a method from an object to its prototype?

Here is an example

function A(name){
  this.name = name;
}

a = new A("brad");

A.prototype = {
  talk: function(){
    return "hello " + this.name;
  }
}

a.talk() // doesn't work
b = new A("john");
b.talk() // works

I got the impression that I awould look for a method talk()in the prototype a, so any modification of the prototype a, before or after a, would be reflected, but it will not. It seems, it is. Can someone explain this to me?

+3
source share
2 answers

This is the difference between modifying and replacing a prototype .

function A(name){
  this.name = name;
}

a = new A("brad");
// Change, don't replace.
A.prototype.talk = function(){
    return "hello " + this.name;
};

a.talk() // works
b = new A("john");
b.talk() // works

Here's what happens:

// Continued from above
var old_proto = A.prototype;

// Nuke that proto
A.prototype = {
talk: function() {
    return "goodbye " + this.name;
}
};

var c = new A("Al");

a.talk() // hello brad
b.talk() // hello john
c.talk() // goodbye Al

old_proto.say_goodbye = function() {
    return "goodbye " + this.name;
};

a.say_goodbye() // goodbye brad
b.say_goodbye() // goodbye john
c.say_goodbye() // TypeError c.say_goodbye is not a function.
+4

: , , . :

function A(name){
  this.name = name;
}

A.prototype = {
  talk: function(){
    return "hello " + this.name;
  }
}

a = new A("brad");

a.talk() // works

( , ).

A , , .

, , "" , .

:

var a = new A("brad");
console.log(a instanceof A) // true

A.prototype = {
  talk: function(){
    return "hello " + this.name;
  }
}

console.log(a instanceof A) // false

, A, A, instanceof , , A.prototype A.

+3

Source: https://habr.com/ru/post/1796121/


All Articles