为什么类和函数在Javascript中的行为不同? [英] Why do classes and functions behave differently in Javascript?
问题描述
我的理解是,所有类本质上都是函数,所有实例本质上都是对象.但是有些事情让我感到困惑.
//Take this for example:
function AnimalFunc(name) {
this.name = name;
this.sayName = function() {
console.log(this.name);
}
}
//And compare it with this:
class AnimalClass {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}
//Now I instantiate them.
cat = new AnimalFunc("cat")
cat.sayName() // -> "cat"
dog = new AnimalClass("dog")
dog.sayName() // -> "dog"
console.log(Object.keys(cat));
console.log(Object.keys(dog));
期望的观测值:
-
typeof(AnimalClass)
和typeof(AnimalFunc)
都返回function
. -
typeof(cat)
和typeof(dog)
都返回object
.
意料之外的观察结果:
- 如果我执行
Object.keys(cat)
,我会得到["name","sayname"]
. - 但是如果我执行
Object.keys(dog)
,我会得到["name"]
.
我的问题是:为什么不将sayname
作为类实例的键?为什么只为函数实例获取它?
第一个带有函数的示例在创建实例时创建了一个新的function属性,因此为Object.keys
提供了一个新键./p>
第二个示例带有一个类,而是将function属性分配给对象的prototype
.因此,实际上并不会创建新的密钥,并且可以通过遍历原型链来找到sayName
函数.
您可以通过执行以下操作来复制类行为:
function AnimalFunc(name) {
this.name = name
}
AnimalFunc.prototype.sayName = function () {
console.log(this.name)
}
如果您要如果愿意,可以通过搜索"javascript原型"来找到更多文章,诸如此类.
My understanding was that all classes were essentially functions, and all instances were essentially objects. But something confused me.
//Take this for example:
function AnimalFunc(name) {
this.name = name;
this.sayName = function() {
console.log(this.name);
}
}
//And compare it with this:
class AnimalClass {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}
//Now I instantiate them.
cat = new AnimalFunc("cat")
cat.sayName() // -> "cat"
dog = new AnimalClass("dog")
dog.sayName() // -> "dog"
console.log(Object.keys(cat));
console.log(Object.keys(dog));
Expected Observations:
typeof(AnimalClass)
andtypeof(AnimalFunc)
both returnfunction
.typeof(cat)
andtypeof(dog)
both returnobject
.
Unexpected Observations:
- If I do
Object.keys(cat)
, I get["name","sayname"]
. - But if I do
Object.keys(dog)
, I get["name"]
.
My question is: why do I not get sayname
as a key for the class instance? Why do I get it only for the function instance?
The first example, with a function, creates a new function property when creating an instance, and therefore, a new key for Object.keys
to pick up.
The second example, with a class, assigns the function property to the object's prototype
instead. Because of this, a new key isn't actually created, and the sayName
function will be found by walking up the prototype chain.
You can replicate the class behavior by doing this:
function AnimalFunc(name) {
this.name = name
}
AnimalFunc.prototype.sayName = function () {
console.log(this.name)
}
Here's some reading if you want to familiarize yourself with JS's prototype model. Can find more articles and such by searching up "javascript prototype", if you like.
这篇关于为什么类和函数在Javascript中的行为不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!