有人可以澄清单词原型和构造函数的含糊不清吗? [关闭]

问题描述 投票:0回答:1

作为一个面向对象的JavaScript新手,我注意到没有太多的重点放在语言“原型”和“构造函数”的模糊性上,这让我想知道我是在正确的轨道上还是误解了整个概念。

例如,here引用以下函数Tree:

function Tree(name) {
  this.name = name;
}

作为原型,当还有一个名为prototype的PROPERTY时,就像在Object.prototype中一样。前者是函数的类型,后者是对象的属性。这有时会产生误导,因为当有人说某个对象的实例继承了其原型的特征时,他们实际上是在说这些实例从名为prototype的对象/函数类型继承了名为prototype的属性(更不用说原型之外还有其他属性)像Object.is()或Object.keys()这样的属性,它们不是继承的!)。

其次,单词构造函数经常被松散地使用,至少在初学者的眼中。例如,当一个人说构造函数的原型时,它们是指person1的函数Person(),其中person1是Person()的实例吗?或者他们是指person1.constructor?当一个人说“构造函数的原型”时,它们是指Object.constructor.prototype还是构造函数Person()的原型?

进一步加剧混乱的是,有时person1.constructor实际上等同于构造函数Person(),实际上它们是两个不同的东西。 person1.constructor的构造函数是person1对象的属性,而函数Person()是一种称为构造函数的函数。如果他们将名为构造函数的函数类型重命名为蓝图,那么可以很容易地看出我的意思是混乱。

javascript oop constructor prototype
1个回答
2
投票

为了说明代码中的问题。

// Tree is the "constructor".
function Tree(name) {
  this.name = name;
}

// Tree.prototype is Tree's "prototype"
// getName method is defined on Tree's prototype
Tree.prototype.getName = function(){
  return this.name
}

// When you instantiate a new Tree
const treeInstance = new Tree()

// The instance's constructor property references the constructor that
// created it. In this case, Tree.
console.log(treeInstance.constructor === Tree)

// The instance's prototype is Tree.prototype
console.log(Object.getPrototypeOf(treeInstance) === Tree.prototype)

// Here's the fun part. The instance has property "name"
console.log(treeInstance.hasOwnProperty('name') === true)

// But getName is NOT on the instance
console.log(treeInstance.hasOwnProperty('getName') === false)

// That's because getName lives on one of the prototypes.
// In this case, Tree.prototype
console.log(treeInstance.getName === Tree.prototype.getName)
console.log(treeInstance.getName === Object.getPrototypeOf(treeInstance).getName)

原型继承通过形成称为“原型”的对象链来工作。如果JS无法在对象上找到某些东西,它会在对象的原型(通常是另一个对象)上查找它。它递归地做到这一点,直到没有更多,最后一个是Object.prototype

上面代码的链看起来像这样:

Object.prototype <- Tree.prototype <- treeInstance

所以...

  • “构造函数”是初始化实例的函数。它始终是一种功能。构造函数中的this是您的实例。
  • 一个“原型”是JS在它无法在实例上找到某些东西时所要求的下一个“事物”。这个“东西”通常是一个对象,但它可以是任何东西。
© www.soinside.com 2019 - 2024. All rights reserved.