代码之家  ›  专栏  ›  技术社区  ›  billy

在原型与构造函数中声明属性?利弊

  •  0
  • billy  · 技术社区  · 7 年前

    我很难理解为什么要在构造函数类或其原型对象上定义属性。

    这里是我对原型的理解 -在原型中声明属性(而不是链接的父对象)可以节省性能,因为每个子对象都不会有自己的父对象属性副本。

    问题:

    **这是否意味着,如果我继承父方法(如下面所示),我将复制对这些方法的引用,还是实际复制**

    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.
    

    child.age = 10; // changed the value for THIS object
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Mark    7 年前

    你把一些事情搞混了。当试图从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

    父母亲 有一个 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)