Javascript 试图更新我对原型树的知识。这里怎么了?

Javascript 试图更新我对原型树的知识。这里怎么了?,javascript,Javascript,根据, 所有JavaScript对象都是继承树的一部分。中的每个对象 树有一个父对象,也称为原型 (孩子的)对象 我在到处玩,以确保我正确理解它。既然myOtherObj从其父项myObj继承了字段x,那么下面不应该打印“lakdas”?为什么它会记录未定义的代码 var myObj = { x:"lakdas" }; var myOtherObj = { y:"lkjaas" }; myOtherObj.prototype = myObj; console.log(myOtherObj.x);

根据,

所有JavaScript对象都是继承树的一部分。中的每个对象 树有一个父对象,也称为原型 (孩子的)对象

我在到处玩,以确保我正确理解它。既然
myOtherObj
从其父项
myObj
继承了字段
x
,那么下面不应该打印
“lakdas”
?为什么它会记录未定义的代码

var myObj = { x:"lakdas" };
var myOtherObj = { y:"lkjaas" };
myOtherObj.prototype = myObj;
console.log(myOtherObj.x); /* Should print "lakdas", right? */

不能通过指定
prototype
属性来更改对象的原型。在许多引擎中,创建对象后根本无法更改原型。可以在对象创建时设置原型:

var myObj = { x:"lakdas" };
var myOtherObj = Object.create(myObj); // sets prototype
myOtherObj.y = "lkjaas";
console.log(myOtherObj.x); // prints "lakdas"
函数具有
prototype
属性-当您将函数用作构造函数时,存储在函数的
prototype
属性中的对象将成为构造对象的原型:

var myObj = { x:"lakdas" };
function foo() {
  this.y = "lkjaas";
}
foo.prototype = myObj;
var myOtherObj = new foo();
console.log(myOtherObj.x); // prints "lakdas"

不能通过指定
prototype
属性来更改对象的原型。在许多引擎中,创建对象后根本无法更改原型。可以在对象创建时设置原型:

var myObj = { x:"lakdas" };
var myOtherObj = Object.create(myObj); // sets prototype
myOtherObj.y = "lkjaas";
console.log(myOtherObj.x); // prints "lakdas"
函数具有
prototype
属性-当您将函数用作构造函数时,存储在函数的
prototype
属性中的对象将成为构造对象的原型:

var myObj = { x:"lakdas" };
function foo() {
  this.y = "lkjaas";
}
foo.prototype = myObj;
var myOtherObj = new foo();
console.log(myOtherObj.x); // prints "lakdas"