Javascript 实例中未显示原型更改

Javascript Prototype changes not showing in instance

我只是想通过尝试一下原型来了解原型,但我不确定我是否做对了。在这个例子中,我本来希望使用在原始函数之外定义的更改来创建原型的新实例:

function Peeps (){
    this.x = "old"
};
Peeps.prototype.x = "new";

var peep1 = new Peeps();
peep1.x; //still "old"

delete peep1.x;
peep1.x; //now "new" 

我知道在最后一行中,x 的新原型值 "shines through" 因为我删除了对象的本机 x(它是 "old")所以它在原型链上向上搜索取而代之的是另一个 x。 我想我的问题是:为什么 x "old" 是对象的第一位?即使原型的属性之一之前已更改,代码是否没有超越新对象的原始 Peeps 原型函数,但是当它在对象中找不到本机 x 时,它会超越原始 Peeps 函数?

我已经通读了这里的其他主题,但我认为我还不太明白其中的原因。如果有人能用自己的话来解释,那就太好了。

对象将在原型链上进行自我检查。你已经在那个对象上设置了一个 属性 ,它会检查它是否存在。如果它不存在,它将开始沿着原型链向上移动。

why was x "old" in the first place for the object? Does the code not look past the original Peeps prototype function for the new object even though one of the prototype's properties got changed before, but when it can't find a native x in the object, it looks beyond the original Peeps function?

没错。原型旨在提供与继承在其他语言中为我们提供的功能类似的功能。你可以用.prototype来表示"most Peepss behave this way"。但是由于您的 "constructor" 函数(通过 new Peeps() 调用)在这个特定实例中设置了一个 属性,因此它将优先于原型。

I have read through other topics on here, but I don't think I quite understand the reasoning yet. If someone could explain it in their own words, that would be great.

以下摘自 an article I wrote,可能对您有所帮助:

JavaScript用特殊的prototype属性来解决其他语言用类解决的问题。考虑以下因素:

function Person(first, last)
{
    this.first = first;
    this.last = last;
}
var john = new Person("John", "Doe");
var mary = new Person("Mary", "Deer");
Person.prototype.full = function() {return this.first + " " + this.last;};
alert(john.full());

这里发生了很多事情。

  1. 我们创建了一个 function,它会在调用时为其 this 对象设置属性。
  2. 我们通过在函数调用之前放置 new 关键字来创建该函数的两个独立实例。这确保 johnmary 引用完全独立的对象,每个对象都有自己的 firstlast 属性。
  3. 我们创建了一个新函数并将其分配给 Person 函数的 prototype 属性 上的 full 属性。 prototype 属性 存在于所有函数中,并允许您定义应存在于从该函数创建的每个对象上的回退属性。
  4. 我们在 john 上调用 full() 函数。 JavaScript 发现 john 对象实际上并没有 full 函数,所以它寻找 Person.prototype.full() 函数并调用它。然而,在该调用中,this 仍然引用 john 对象。

你这里有 2 个东西:

Peeps.x(在 Peeps 函数内部定义) Peeps.prototype.x(定义外)

也许答案就在这里:当您从 Peeps 中删除 "x" 时,它会使用现有原型作为 x 的模板。这就是您获得这些价值的原因。