Javascript原型属性'

Javascript Prototype Property'

我遵循 javascript 中关于 'function Constructors' 和 'Prototype Chains' 的逻辑,但是我正在尝试解决原型链的重要性,即它究竟需要多长时间。

Constructor 函数对于创建对象很有用,--对吧?因此,在使用 'Function Constructor' 创建对象时,该对象是否已经拥有指向链中更高层 'global object' 的指针? ...如果是这样,为什么还要包含这个 'prototype property'?要么... 原型 属性 实际上 'instantiate' 是 link 函数对象到全局对象的继承链。

如果原型 属性 没有在对象的局部上下文和全局上下文之间实例化 link 为什么要包含它?如果我从函数构造函数的属性列表中省略原型 属性 会发生什么变化?

我只需要一个清晰、简洁的原型目的背后的原因 属性 ,在这一点上有一定道理,但就它如何为继承链做出贡献而言仍然没有意义。

感谢阅读。

如果执行下面这行代码

function Dog(){
    this.constBreed = "Pug";
}
Dog.prototype.breed = "Bull";

var newDog = new Dog();

console.log(newDog);

日志会给你下面的结果

Dog {constBreed: "Pug"}
    constBreed: "Pug"
    __proto__:
        breed: "Bull"
        constructor: ƒ Dog()
        __proto__: Object

这里构造函数变量"constBreed"直接附加到"newDog"对象,原型属性"breed"到proto链.

所以这非常有用,因为我们可以从 Dog() 函数创建多个新的 Dog 变量,并通过更改 Dog() 函数本身的 protopye.breed 一次更改它们的品种。

对于构造函数变量"constBreed",它只是为您从 Dog() 函数创建的每个新对象复制并重新初始化。

I just need a clear, concise reason behind the purpose of the prototype property , which at this point makes some sense but still no sense in terms of how it contributes to the inheritance chain.

我们以这段代码为例:

function Foo(prop) {
  this.fooProperty = prop
}

Foo.prototype.greetFoo = function() {
  console.log('hi from foo')
}

function Bar(prop1, prop2) {
  Foo.call(this, ...arguments)
  this.barProperty = prop2
}

// Replace the default Bar.prototype object with one that links to Foo.prototype
Bar.prototype = Object.create(Foo.prototype)
Bar.prototype.greetBar = function() {
  console.log('hi from bar')
}

const barInstance1 = new Bar('baz', 'rar')
const barInstance2 = new Bar('qum', 'yas')

barInstance1.greetFoo()
barInstance2.greetFoo()
barInstance1.greetBar()
barInstance2.greetBar()

以上将产生以下原型链:

Object.prototype <- Foo.prototype <- Bar.prototype <- barInstance1
                    > greetFoo()     > greetBar()     > fooProperty = 'baz'
                                                      > barProperty = 'rar'
                                                   <- barInstance2
                                                      > fooProperty = 'qum'
                                                      > barProperty = 'yas'

在传统的 OOP 中,classes 是 "blueprints",实例是根据实例化 class 的继承层次结构的 "flattened/merged" 蓝图创建的对象。 JS "inheritance" 的工作方式与此不同。 JS 继承使用链接的层次结构,实时对象,而不是蓝图。

当你在实例上访问实例没有的东西时(比如greetFoo()greetBar()),JS会递归地查找链来找到它。该链可能涉及其他原型,具有更多功能。这就是 JS "code sharing" 的工作原理。

在上面的例子中,

  • barInstance1barInstance2 链接到 Bar.prototype。两个实例现在都有 greetBar().
  • Bar.prototype 也链接到 Foo.prototype,这意味着实例也得到 greetFoo.
  • 最后,Foo.prototype 链接到内置 Object.prototype,使所有实例都可以访问所有本机对象方法,如 hasOwnPropertytoString()