问题描述
我想知道 - JavaScript 对象、类和函数之间有什么区别?我认为类和函数是对象的类型是否正确?
I was wondering - what's the difference between JavaScript objects, classes and functions?Am I right in thinking that classes and functions are types of objects?
类和函数的区别是什么?或者它们真的是同一个东西,只是它们的术语根据它们的使用方式而变化?
And what distinguishes a class from a function? Or are they really the same thing, just the term for them changes according to how they are used?
function func() { alert('foo'); } // a function
func(); // call the function - alerts 'foo'
var func2 = function () { alert('hello'); } // acts the same way as 'func' surely?
func2(); // alerts 'hello'
var Class = function() { alert('bar'); }; // a class
var c = new Class(); // an istance of a class - alerts 'bar'
当然,类有方法和属性并且可以实例化 - 但是,我可以对任何旧函数做同样的事情 - 或者不?
Sure, classes have methods and properties and can be instantiated - but then, I could do the same with any old function - or not?
推荐答案
正如您现在必须知道的那样,JavaScript 中没有类.相反,通过在函数调用前加上 new
关键字,可以使 JavaScript 中的函数表现得像构造函数.这被称为 构造函数模式.
As you must already be aware by now there are no classes in JavaScript. Instead functions in JavaScript may be made to behave like constructors by preceding a function call with the new
keyword. This is known as the constructor pattern.
在 JavaScript 中,除了原始数据类型(布尔值、数字和字符串)和 undefined
之外,一切都是对象.另一方面, null
实际上是一个对象引用,即使您起初可能不这么认为.这就是 typeof null
返回 "object"
的原因.
In JavaScript everything is an object except for the primitive data types (boolean, number and string), and undefined
. On the other hand null
is actually an object reference even though you may at first believe otherwise. This is the reason typeof null
returns "object"
.
JavaScript 中的函数类似于 Lua 中的 functables(即它们是可调用对象).因此,可以使用函数代替对象.同样,数组也是 JavaScript 中的对象.另一方面,对象可以被认为是关联数组.
Functions in JavaScript are similar to functables in Lua (i.e. they are callable objects). Hence a function can be used in place of an object. Similarly arrays are also objects in JavaScript. On the other hand objects can be thought of as associative arrays.
然而,最重要的一点是 JavaScript 中没有类,因为 JavaScript 是一种原型的面向对象语言.这意味着 JavaScript 中的对象直接从其他对象继承.因此我们不需要类.我们需要的只是一种创建和扩展对象的方法.
The most important point however is that there are no classes in JavaScript because JavaScript is a prototypal object oriented language. This means that objects in JavaScript directly inherit from other objects. Hence we don't need classes. All we need is a way to create and extend objects.
阅读以下主题以了解有关 JavaScript 中原型继承的更多信息:原型继承相对于经典继承的好处?
Read the following thread to learn more about prototypal inheritance in JavaScript: Benefits of prototypal inheritance over classical?
这篇关于对象 vs 类 vs 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!