javascript:函数和类之间的区别是什么 [英] javascript: what's the difference between a function and a class

查看:124
本文介绍了javascript:函数和类之间的区别是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道函数和类之间有什么区别。
两者都使用关键字函数,两者之间有明显的区别吗?

I am wondering what's the difference between function and class. Both using the keyword function, is there obvious distinction between those two?

推荐答案

技术上没有课程,他们这两个都只是功能。任何函数都可以作为构造函数使用关键字 new 调用,该函数的prototype属性用于从该对象继承方法。

There is technically no class, they're both just functions. Any function can be invoked as a constructor with the keyword new and the prototype property of that function is used for the object to inherit methods from.

类别仅用于概念性地描述上述做法。

"Class" is only used conceptually to describe the above practice.

所以当有人对你说制作颜色类或其他什么时,你会这样做:

So when someone says to you "make a color class" or whatever, you would do:

function Color(r, g, b) {
    this.r = r;
    this.g = g;
    this.b = b;
}

Color.prototype.method1 = function() {

};

Color.prototype.method2 = function() {

};

当你将其分解时,只有一个函数和一些名为<$ c的属性的赋值该函数的$ c> prototype ,所有
泛型javascript语法,没什么好看的。

When you break it down, there is simply a function and some assignments to a property called prototype of that function, all generic javascript syntax, nothing fancy going on.

这一切都变得有些神奇了你说 var black = new Color(0,0,0)。然后,您将获得一个对象,其属性为 .r .g .b 。那个对象
也会有一个隐藏的[[prototype]]链接到 Color.prototype 。即使 .method1()黑色对象。

It all becomes slightly magical when you say var black = new Color(0,0,0). You would then get an object with properties .r, .g and .b. That object will also have a hidden [[prototype]] link to Color.prototype. Which means you can say black.method1() even though .method1() does not exist in the black object.

这篇关于javascript:函数和类之间的区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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