我很难理解为什么要在构造函数类或它的原型对象上定义属性。
这里所理解的原型--在原型中声明属性(而不是链接的父对象)保存了性能,因为每个子对象都没有自己的父对象属性的副本。
问题:,但我认为您不能从非原始类型复制值,即函数对象只传递引用.并且只能从原语中复制?
**这是否意味着,如果我像下面这样继承父母的方法,我将复制对方法的引用,还是实际复制?**
function Parent() {
this.name = "jeff";
}
var child = new Parent();
console.log(child.name); /// is copied from parent or the reference is copied?? 在下面的例子中,我引用了原型..。对吗?
Parent.prototype.age = 9;
child.age // I looks at the parent class, then reference to prototype.age.*问题2:*如果我可以更改特定对象的prototype.age,那么我实际上复制了这个值,对吗?那么,有什么意义,即**
child.age = 10; // changed the value for THIS object发布于 2019-01-12 03:24:19
你有几件事搞混了。当试图从OO的角度理解javascript时,这种情况很常见,因为这并不是一个非常合适的方法。也许这会有一点帮助:
这只是一个函数(使用new调用时)返回一个对象:
function Parent() {
// create a new object and call it this
this.name = "jeff";
}它返回的对象每次都是新创建的,该对象就是this所引用的对象。因此,每次运行它时,它都会生成一个对象,为该对象提供一个name参数,将其设置为jeff并重新运行。如果使用动态属性,则更容易查看:
function Parent() {
console.log("creating a new object and a new value")
this.value = Math.floor(Math.random()* 100000);
}
var child1 = new Parent();
console.log("child1: ", child1)
var child2 = new Parent();
console.log("child2: ", child2)
值不是继承的,它只是在调用函数时分配给对象。Parent只是一个函数。
与所有函数一样,Parent有一个prototype属性。当它用new创建一个对象时,它会将该对象链接到它的prototype。如果您试图查找返回对象上的属性,却找不到它,javascript将查看父原型。现在分配child.age = 10时,子节点有自己的年龄属性。它不再需要看原型。只有当它没有自己的属性时,它才会在原型上查找属性。
function Parent() {
this.name = "Jeff"
}
Parent.prototype.age = 9
var child = new Parent();
// child has no age prop so it looks on the prototype:
console.log(child.age)
console.log("Has age:", child.hasOwnProperty('age'))
child.age = 20
// now child has its own age property. It doens't look at the prototype
console.log("Has age:", child.hasOwnProperty('age'))
console.log(child.age)
https://stackoverflow.com/questions/54156403
复制相似问题