0

I learned about prototype and proto and i think i understand it but this just doesn't make sense? Can somebody explain to me why accessing directly Object like this doesn't work.

function createObj() {
  this.name = 'user';
  this.prezime = 'user';
}

var obj1 = new createObj();

createObj.prototype.__proto__.toString = function () {
  return 'works';
}   //obj1.toString() returns 'works'   

createObj.__proto__.__proto__.toString = function () {
  return 'this works as well';
}   //obj1.toString() returns 'this works as well  '

//Then why this doesn't work: 

Object.toString = function () {
  return true;
}

From my understanding I am directly changing Object object.

So when I do obj1.toString() shouldn't it go to prototype and then proto inside prototype and find toString() like it does from last two examples?

Mark
  • 5,089
  • 2
  • 20
  • 31
Vukasin Sevo
  • 117
  • 1
  • 7
  • Don't use `__proto__`. If it's pre-es5 it's non-standard, if it's post-es5 then you have `Object.getPrototypeOf/Object.setPrototypeOf`. Note that the latter will likely trigger a console warning. There's pretty much never a good reason to access `__proto__` directly. – Jared Smith Nov 08 '18 at 21:52

1 Answers1

1

This is because you're setting a property on the Object constructor, not the Object prototype when you say Object.toString = ....

Trying to understand the difference between prototype and constructor in JavaScript

If you change Object.toString = ... to Object.prototype.toString = ... you get your desired result:

function createObj() {
  this.name = 'user';
  this.prezime = 'user';
}

var obj1 = new createObj();

createObj.prototype.__proto__.toString = function() {
  return 'works';
} //obj1.toString() returns 'works'   

console.log(obj1.toString());

createObj.__proto__.__proto__.toString = function() {
  return 'this works as well';
}

console.log(obj1.toString());

Object.prototype.toString = function() {
  return true;
}

console.log(obj1.toString())
mhodges
  • 10,938
  • 2
  • 28
  • 46