最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

class - How do you make classes in JavaScript? - Stack Overflow

programmeradmin1浏览0评论

How do you guys make "classes" in JavaScript!?

I am using:

function classFoo()
{
   var classLevelVariable = 0;

   this.classFunction = function()
   {
      alert("The classFunction has been called.");
      classFunction2(); //Crash.  classFunction2 is "undefined."  
   }

   this.classFunction2 = function()
   {
      alert("classFunction2 called.");
   }
}

I never was able to get constructors to work. Tried

this.New = function(arguments)

Which worked once, but not in a second class. So, I have now given up on those entirely, using my own "Initialize" functions which act as constructors.

The weirdness with it working once, but not twice, makes me think typographical errors between the two classes... but I think in 19 years of coding, that that probably isn't it.

I'm using Chrome's debugger, and I am not receiving any errors besides the second function being undefined when being called.

How do you guys make "classes" in JavaScript!?

I am using:

function classFoo()
{
   var classLevelVariable = 0;

   this.classFunction = function()
   {
      alert("The classFunction has been called.");
      classFunction2(); //Crash.  classFunction2 is "undefined."  
   }

   this.classFunction2 = function()
   {
      alert("classFunction2 called.");
   }
}

I never was able to get constructors to work. Tried

this.New = function(arguments)

Which worked once, but not in a second class. So, I have now given up on those entirely, using my own "Initialize" functions which act as constructors.

The weirdness with it working once, but not twice, makes me think typographical errors between the two classes... but I think in 19 years of coding, that that probably isn't it.

I'm using Chrome's debugger, and I am not receiving any errors besides the second function being undefined when being called.

Share Improve this question edited Jul 19, 2010 at 4:26 Michael Petrotta 60.9k27 gold badges152 silver badges181 bronze badges asked Jul 19, 2010 at 4:21 JKZJKZ 1491 silver badge3 bronze badges 17
  • 2 @John: review the edit history. I hope I've edited the question sufficiently to make it a reasonable one. – Michael Petrotta Commented Jul 19, 2010 at 4:30
  • 3 You can't call classFunction2() when it is a method of classFoo() You have to have this.classFunction2() if your inside classFoo(). – qw3n Commented Jul 19, 2010 at 4:31
  • 4 @John: we'll have to agree to disagree. You should note that his question would have been closed, rather quickly, if it were to stand unedited. – Michael Petrotta Commented Jul 19, 2010 at 4:43
  • 1 I'm surprised that they can give CS degrees out to people with such paradigmatic ignorance. It's called a "prototype" and it's not the same thing as a class. Despite your CS prof's insistence, Java and C++ are not the gold standard of OOP, nor is OOP the be-all-end-all of programming. It seems like you have a very poor strategy for ascertaining facts, since Javascript and Actionscript both implement the same goddamn spec, ECMAScript. – Jesse Dhillon Commented Jul 19, 2010 at 5:28
  • 1 Javascript is a Prototype-based programming. A style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes. Prototype-based programming (en.wikipedia.org/wiki/Prototype-based_programming) - Class-based programming (en.wikipedia.org/wiki/Class-based_programming) – pauloh Commented Jul 19, 2010 at 17:16
 |  Show 12 more comments

6 Answers 6

Reset to default 8

Javascript does not use class-based inheritance. So, you can't make classes in Javascript, except to emulate them using workarounds that are IMHO clumsy and complicated.

Javascript is a prototypal language. Using the new keyword creates a new object based on the prototype property of the constructor object.

You can get an idea how you might use prototypal inheritance to instantiate a new object based on a prototypal object here: http://javascript.crockford.com/prototypal.html

I feel that your original rant (see question's revision history) deserves a response. It's very much against the spirit of programming and computer science, in my opinion, to declare a language broken merely because you can't make it go.

Please pardon me if I offend you when I say that I'm surprised that they can give CS degrees out to people with such paradigmatic ignorance. When I went to school, which was only about 5 years ago, I did my assignments in 6 different languages: MIPS, Verilog, Scheme, Java, C/C++ and Python. We used many paradigms, including functional and OOP but other styles as well. If you were not exposed to these different perspectives, none of which are new, your education is not complete.

Has it occurred to you that what you consider to be canonical OOP is merely one formulation of the OOP principles? In Javascript objects instantiate from a "prototype," and it's not the same thing as a class. When you expect it to work like a class-based OOP language, it will not meet your expectations. Java and C++ are not the gold standard of OOP, nor is OOP the be-all-end-all of programming.

When one considers the amazing apps that have been written in Javascript in the past 3-5 years, it's amazing that a person can make a statement like this:

One would think we would apply our best coding practices over the last six decades into it. No. Of course not. What do we have? Functions inside of functions... some weird bastardization of classes. Complete with no consistency...

To say that, despite the brilliant achievements made by teams of brilliant Javascript developers, the language is broken because you have difficulty understanding it is, well, astonishing.

Please consider that, instead of the language being flawed, you may not presently possess the perspective necessary to understand it.


PS, You mentioned that you are "using JavaScript to AVOID FLASH!" It seems like you have a very poor strategy for ascertaining facts, since Javascript and Actionscript both implement the same spec: ECMAScript.

JavaScript is a prototype based programming language. The concept of a class does not exist or the concept of a class is the same as an object. It's quite different from say the Java programming language. Do not be fooled by thier names, the similaries end there.

I asked this question I while back. I got an answer with a nice link to these presentation slides by John Resig. Look though that and see if it helps with understanding JavaScript and prototype chains.

Here is a good article on sitepoint.com about Object Oriented Programming in JavaScript.

This one on javascriptkit.com is more straightforward.

You can use a function to creates an object set its properties and functions like this:

person = new Object()
person.name = "Tim Scarfe"
person.height = "6Ft"

person.run = function() {
    this.state = "running"
    this.speed = "4ms^-1"
}

or use constructors:

function person(name,height,speed){
    this.name = name;
    this.height = height;
    this.speed = speed;
}

var p1=new person('tom', '6ft','15kmph');

alert(p1.height);

or you can use prototyping to extend objects:

person.prototype.sayHello = function(){alert("Hi, I'm " + name;}

var p2 = new person('sam', '5.9ft', '12kmph');
p2.sayHello();//alert-> Hi, I'm sam

more in-depth details are on the linked pages.

JavaScript is a Prototyping Language, so things are a little different.

Here is a code snippet to explain:

(function(){ // create an isolated scope
    // My Object we created directly
    var myObject = {
        a: function(x,y) {
            console.log('a');
        },
        b: function(x,y) {
            console.log('b');
            this.a(x,y);
        }
    };
})();

(function(){ // create an isolated scope

    // Create a Object by using a Class + Constructor
    var myClass = function(x,y) {
        console.log('myClass: constructor');
        this.b(x,y);
    };
    myClass.prototype = {
        a: function(x,y) {
            console.log('myClass: a');
        },
        b: function(x,y) {
            console.log('myClass: b');
            this.a(x,y);
        }
    };

    // Define a function that should never inherit
    myClass.c = function(x,y) {
        console.log('myClass: c');
        this.a(x,y);
    };

    // Create Object from Class
    var myObject = new myClass();
    // Will output:
    // myClass: constructor
    // myClass: b
    // myClass: a

    // Define a function that should never inherit
    myObject.d = function(x,y) {
        console.log('myObject: d');
        this.a(x,y);
    };

    // Test the world is roung
    console.log(typeof myClass.c, 'should be undefined...');
    console.log(typeof myClass.d, 'should be function...');
})();

(function(){ // create an isolated scope
    // If you are using a framework like jQuery, you can obtain inheritance like so

    // Create a Object by using a Class + Constructor
    var myClass = function(x,y) {
        console.log('myClass: constructor');
        this.b(x,y);
    };
    myClass.prototype = {
        a: function(x,y) {
            console.log('myClass: a');
        },
        b: function(x,y) {
            console.log('myClass: b');
            this.a(x,y);
        }
    };

    // Create new Class that inherits
    var myOtherClass = function(x,y) {
        console.log('myOtherClass: constructor');
        this.b(x,y);
    };
    $.extend(myOtherClass.prototype, myClass.prototype, {
        b: function(x,y) {
            console.log('myOtherClass: b');
            this.a(x,y);
        }
    });

    // Create Object from Class
    var myOtherObject = new myOtherClass();
    // Will output:
    // myOtherClass: constructor
    // myOtherClass: b
    // myClass: a
})();

(function(){ // create an isolated scope
    // Prototypes are useful for extending existing classes for the future
    // Such that you can add methods and variables to say the String class
    // To obtain more functionality
    String.prototype.alert = function(){
        alert(this);
    };
    "Hello, this will be alerted.".alert();
    // Will alert:
    // Hello, this will be alerted.
})();

There are libraries to help with this such as:

  • Mootools Class: http://mootools.net/docs/core/Class/Class
  • jQuery BalClass: http://www.balupton.com/projects/jquery-sparkle/#using

By using the Prototype javascript framework.

发布评论

评论列表(0)

  1. 暂无评论