【发布时间】: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