Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

javascript: what's the difference between a function and a class

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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() {

};

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...