对象对象无法正常工作

时间:2018-11-08 21:31:46

标签: javascript object prototype proto

我了解了原型和原型,我想我理解了,但这是没有道理的吗?有人可以向我解释为什么不能像这样直接访问对象吗?

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;
}

据我了解,我是直接更改对象object

因此,当我执行obj1.toString()时,不应该转到prototype并 然后在protoprototype并像上两个示例一样找到toString()

1 个答案:

答案 0 :(得分:0)

这是因为您说{{1}时是在Object 构造函数而不是Object 原型上设置属性}。

Trying to understand the difference between prototype and constructor in JavaScript

如果将Object.toString = ...更改为Object.toString = ...,则会得到所需的结果:

Object.prototype.toString = ...