Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What style do you use for creating a "class"?

Tags:

There are a few ways to get class-like behavior in javascript, the most common seem to be prototype based like this:

function Vector(x, y, x) {     this.x = x;     this.y = y;     this.z = z;     return this; }  Vector.prototype.length = function () { return Math.sqrt(this.x * this.x ... ); } 

and closure based approaches similar to

function Vector(x, y, z) {     this.length = function() { return Math.sqrt(x * x + ...); } } 

For various reasons the latter is faster, but I've seen (and I frequently do write) the prototype version and was curious as to what other people do.

like image 439
olliej Avatar asked Aug 09 '08 00:08

olliej


People also ask

How do you write a class in style?

If you want to use a class, use a full stop (.) followed by the class name in a style block. Next, use a bracket called a declaration block that contains the property to stylize the element, such as text color or text size. CSS Classes will help you stylize HTML elements quickly.

What is a style class?

8.3. Style Classes. CSS2 classes let you create, at the document level or in an external style sheet, several different styles for the same elements, each distinguished by a class name. To apply the style class, name it as the value of the class attribute in its corresponding tag.

How do you create a class style in HTML?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)

What is a class CSS?

What is a CSS class? A CSS class is an attribute used to define a group of HTML elements in order to apply unique styling and formatting to those elements with CSS.


2 Answers

Assigning functions to the prototype is better (for public methods) because all instances of the class will share the same copy of the method. If you assign the function inside the constructor as in the second example, every time you create a new instance, the constructor creates a new copy of the length function and assigns it to just that one instance.

However this latter technique is useful if you want each copy to have it's own copy, the main use of that being to do private/privileges methods which have access to private variables declared inside the constructor and inherited via the closure mechanism.

Douglas Crockford has a good summary.

like image 115
Kieron Avatar answered Sep 18 '22 12:09

Kieron


There is also the object literal approach to the prototype:

var Vector = function(){};  Vector.prototype = {   init:function(x,y,z) {     this.x = x;     this.y = y;     this.z = z;   },   length:function() {     return Math.sqrt(x * x + ...);   } };  var v1 = new Vector(); v1.init(1,2,3); 
like image 21
JayTee Avatar answered Sep 21 '22 12:09

JayTee