对象vs类vs函数 [英] Object vs Class vs Function

查看:165
本文介绍了对象vs类vs函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 - 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?

什么区别类和函数?

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中没有类。相反,JavaScript中的函数可以通过使用 new 关键字前面的函数调用来表现为构造函数。这称为构造函数模式

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 believe at first otherwise. This is the reason typeof null returns "object".

JavaScript中的函数与Lua中的函数类似(即它们是可调用对象)。因此,可以使用函数代替对象。类似地,数组也是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函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆