Javascript "classes" (without frameworks)

I am doing my first javascript project that uses objects heavily. Due to how this works, almost all user objects are executed as follows:

namespaceobj = {};
namespaceobj.subobject = {};
namespaceobj.subobject.somefunction = function(arg, uments) {
    // Do Stuff
}
namespaceobj.subobject.somedata = 10;
namespaceobj.othersubject = {};
namespaceobj.othersubject.somefunction = function(some, args) {
    // Do more stuff
}
// More subobjects etc.

This is normal, since all user objects have only one instance (examples of sub-objects are the user interface, tools, general data, etc.).

However, I saw that the code did something like this (the syntax is probably incorrect, it's just from memory, seeing similar code)

function SomeClass() {
    this.somedata = 42;
    this.somefunction = function(a, few, args) {
        // Do Stuff
    }
}
// More classes and stuff
// Elsewhere:
someInstance = new SomeClass(); // AFA I recall, new was optional
someInstance.somefunction();

Can someone explain how the “classes” in the second example work, and any errors that I may encounter when using them.

+3
source share
4 answers

, , , : -

function SomeClass() {
    var somedata = 42;
    this.somefunction = function(a, few, args) {
    // Do Stuff like:-
    return somedata + a;
  }
}
// More classes and stuff
// Elsewhere:
someInstance = new SomeClass(); // AFA I recall, new was optional
someInstance.somefunction(15);  //returns 57

, , , , ( , SomeClass() , to someInstance). , , , somedata , - .

somedata , , SomeClass.

, Javascript OO-, . , OO Javascript .

+2

, , , - ( ) OOP JavaScript. , , , , ( ) .

JavaScript - (OOP):

JavaScript - - - . , . JS , # Java. , JavaScript . - ; , .

+2

, . , . , , . , , , .

0

, , , "", , . , . .

, , .

, , "" . - , // , . , , - .

Javascript hashtables . "object.something", , . , invocation "object.foo(...)", "foo" "". "foo" "", "foo" "". , - .

"foo" .. , , foo .

0

Source: https://habr.com/ru/post/1708511/


All Articles