javascript 对象 vs 类 vs 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17525450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:39:24  来源:igfitidea点击:

Object vs Class vs Function

javascriptclassoop

提问by Sean Bone

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?

我想知道 - JavaScript 对象、类和函数之间有什么区别?我认为类和函数是对象类型是否正确?

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?

当然,类有方法和属性并且可以被实例化——但是,我可以对任何旧函数做同样的事情——或者不?

采纳答案by Aadit M Shah

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 newkeyword. This is known as the constructor pattern.

正如您现在必须知道的那样,JavaScript 中没有类。相反,JavaScript 中的函数可以通过在函数调用前加上new关键字来表现得像构造函数。这称为构造函数模式

In JavaScript everything is an object except for the primitive data types (boolean, number and string), and undefined. On the other hand nullis actually an object reference even though you may at first believe otherwise. This is the reason typeof nullreturns "object".

在 JavaScript 中,除了原始数据类型(布尔值、数字和字符串)和undefined. 另一方面null,实际上是一个对象引用,即使您起初可能不这么认为。这就是typeof null返回的原因"object"

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 中的函数类似于 Lua 中的 functables(即它们是可调用对象)。因此,可以使用函数代替对象。同样,数组也是 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 中没有类,因为 JavaScript 是一种原型的面向对象语言。这意味着 JavaScript 中的对象直接从其他对象继承。因此我们不需要类。我们所需要的只是一种创建和扩展对象的方法。

Read the following thread to learn more about prototypal inheritance in JavaScript: Benefits of prototypal inheritance over classical?

阅读以下主题以了解有关 JavaScript 中原型继承的更多信息:原型继承优于经典继承?

回答by Neoaptt

Update 2015

2015 年更新

There are classes in javascript they just aren't used on older browsers. enter image description here

javascript 中有一些类,它们只是不在旧浏览器上使用。 在此处输入图片说明

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

It has constructors, extentions, and the like.

它有构造函数、扩展等。

class Cat { 
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(this.name + ' makes a noise.');
  }
}

class Lion extends Cat {
  speak() {
    super.speak();
    console.log(this.name + ' roars.');
  }
}

回答by loxxy

A Class in JS:

JS中的一个类:

function Animal(){  

    // Private property
    var alive=true;

    // Private method
    function fight(){ //... }   

    // Public method which can access private variables
    this.isAlive = function() { return alive; } 

    // Public property
    this.name = "Joe";
}

// Public method
Animal.prototype.play = function() { alert("Bow wow!"); }

// .. and so on

Now when you create it's object

现在当你创建它的对象时

var obj = new Animal();

You can expect anything of this object as you would from objects in other language. Just the efforts to achieve it, was a bit different. You should also be looking at inheritance in JS.

您可以像从其他语言的对象中一样期待此对象的任何内容。只是努力实现它,有点不同。您还应该查看JS中的继承



Getting back too your question, I'll reword it as:

回到你的问题,我将其改写为:

Class  : A representation of a set with common properties.
object : One from the set with the same properties.


var Class = function() {alert('bar');}; // A set of function which alert 'bar'
var object = new Class();               // One of the functions who alert's 'bar'.

回答by mishik

JavaScript does not have classes, and functions are actually objects in JavaScript (first-class citizens). The only difference that function objects have is that they are callable.

JavaScript 没有类,函数实际上是 JavaScript 中的对象(一等公民)。函数对象的唯一区别是它们是可调用的

function func() { alert('foo'); } // a function- Correct

function func() { alert('foo'); } // a function- 正确的

func(); // call the function - alerts 'foo'- Correct

func(); // call the function - alerts 'foo'- 正确的

var func2 = function () { alert('foo'); } // same as 'func' surely?- Nope, func2is a different object, that apparently does the same thing when called.

var func2 = function () { alert('foo'); } // same as 'func' surely?- 不,func2是一个不同的对象,它在调用时显然做同样的事情。

var Class = function() { alert('bar'); };- It's a function with no name stored in variable Class.

var Class = function() { alert('bar'); };- 这是一个没有名称存储在变量中的函数Class

var c = new Class();- Calls function stored in Classsupplying new empty object as thisand returning that object. Functions called as new functionA()are expected to work as constructors and prepare a newly created object (this). In your case - constructor does nothing with the object and just alerts bar.

var c = new Class();- 调用存储在Class提供新的空对象作为this并返回该对象的函数。调用 as 的函数new functionA()应作为构造函数工作并准备新创建的对象 ( this)。在您的情况下,构造函数对对象不执行任何操作,只是发出警报bar

回答by ShanaSkydancer

You also get classes in ES6 that look like this:

您还可以在 ES6 中获得如下所示的类:

//class
class Cat {
    //constructor
    constructor() {
        this.name = 'Snowball';
    }

    //method
    meow() {
        console.log('Hello, nyah! My name is ' + this.name + ' nyah!~');
    }
};

回答by Tala

There are no classes in javascript. But, there are ways to make a function to behave like a class in other languages.

javascript 中没有类。但是,有一些方法可以使函数表现得像其他语言中的类。

A very good explanation is given here 3 way to define a class in js

这里给出了很好的解释3种在js中定义类的方法

Also, found a very good reference for OOP in Javascript

另外,在 Javascript 中找到了一个很好的OOP参考

回答by Prasad Honrao

Object is the base type in JavaScript i.e. all the user defined data types inherits from Object in one way or another. So if you define a function or a class [note as of now JS doesn't support class construct, but its proposed in ECMAScript version 6], it will implicitly inherit from Object type.

Object 是 JavaScript 中的基本类型,即所有用户定义的数据类型都以某种方式从 Object 继承。所以如果你定义了一个函数或一个类[注意目前 JS 不支持类构造,但它在 ECMAScript 版本 6 中提出],它将隐式继承自 Object 类型。

Classes are really used for encapsulating logical functions and properties into one type / entity and you can 'new' it up using constructor syntax. So if you define a 'Customer' class, you can instantiate it multiple times and each instance / object can have different values. They can even share the values if you define class level value using prototype.

类实际上用于将逻辑函数和属性封装到一种类型/实体中,您可以使用构造函数语法对其进行“新建”。因此,如果您定义一个“客户”类,您可以多次实例化它,并且每个实例/对象可以具有不同的值。如果您使用原型定义类级别的值,它们甚至可以共享这些值。

Since JS doesn't support class construct at the moment, functions can really act as individual method as well as container for other functions or types.

由于 JS 目前不支持类构造,函数实际上可以作为单独的方法以及其他函数或类型的容器。

I hope with ECMAScript 6 we will have clear separation between these constructs similar to what we have in other languages like C#, Java etc.

我希望在 ECMAScript 6 中,我们能像在其他语言(如 C#、Java 等)中一样,将这些结构清晰地分开。