【问题标题】:Difference between object and object created using class使用类创建的对象和对象之间的区别
【发布时间】:2020-05-17 18:28:12
【问题描述】:
    var cat = {
     name: "Gus",
     color: "gray",
     age: 15,
     printInfo: function() {
      console.log("Name:", this.name, "Color:", this.color, "Age:", this.age); 
       nestedFunction = function() {
         console.log("Name:", this.name, "Color:", this.color, "Age:", this.age)
       }
       nestedFunction();
     }
    }
    cat.printInfo()

//PRINTS : Name: Gus 颜色: gray 年龄: 15 -- printInfo 打印

//PRINTS : Name: undefined Color: undefined Age: undefined -- 由nestedFunction打印

    class info {
     constructor(name,color,age){
     this.name = name
     this.color = color
     this.age = age
    }
    printInfo = function(){
      console.log("Name:", this.name, "Color:", this.color, "Age:", this.age); 
      nestedFunction=function(){
        console.log("Name:", this.name, "Color:", this.color, "Age:", this.age); 
      }
      nestedFunction();  
     }
    }
    var obj=new info("thomas","orange","26") 
    obj.printInfo()

//PRINTS : 姓名:thomas 颜色:橙色 年龄:26(printInfo 印刷)

ReferenceError: nestedFunction 未定义(之后抛出错误) 在第一种情况下,直接对象是制作的,而在第二种情况下,对象是使用类制作的。

但是输出不同 在类对象中,它会抛出错误,因为 nestedFunction 未定义

请告诉我直接对象和使用类模板制作的对象之间的区别。

【问题讨论】:

    标签: javascript class object this


    【解决方案1】:

    在这两种情况下,您都忘记了 nestedFunction 声明之前的 var 以及当您将 this 作为该函数的参数时,然后在这两种情况你的代码都有效:

    var nestedFunction = function(cat) {
        console.log("Name:", cat.name, "Color:", cat.color, "Age:", cat.age)
    }
    nestedFunction(this);
    

    顺便说一句:在第二种情况下,避免使用类、new 关键字及其副作用,并使用第一种情况中的对象来代替行为更简洁委托:

    var cat = {
        setData(name, color, age) {
            this.name = name;
            this.color = color;
            this.age = age;
        },
        printInfo: function() {
            console.log("Name:", this.name, "Color:", this.color, "Age:", this.age); 
            var nestedFunction = function(cat) {
                console.log("Name:", cat.name, "Color:", cat.color, "Age:", cat.age)
            }
            nestedFunction(this);
        }
    }
    
    var gus = Object.create(cat);        //behavior delegation
    var thomas = Object.create(cat);     //behavior delegation
    
    gus.setData("Gus", "gray", 15);
    thomas.setData("thomas", "orange", 26);
    
    gus.printInfo();                     //Name: Gus Color: gray Age: 15
                                         //Name: Gus Color: gray Age: 15
    thomas.printInfo();                  //Name: thomas Color: orange Age: 26
                                         //Name: thomas Color: orange Age: 26
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      • 1970-01-01
      • 2012-01-12
      • 2014-10-19
      • 2017-10-04
      相关资源
      最近更新 更多