简体   繁体   中英

Javascript - How to define a Constructor

I have an object written like this:

Object1.prototype = {
    isInit: false,
    Get : function (){}
} 

Now I'd like to add a constructor which takes one parameter. How can I do it?

Class declaration

var User = function(name, age) { // constructor
}

User.prototype = {}

Instance variables (members)

var User = function(name, age) {
    this.name = name;
    this.age = age;
}

User.prototype = {}

Static variables

var User = function(name, age) {
    this.name = name;
    this.age = age;
}

User.prototype = {
    staticVar: 15,
    anotherStaticVar: 'text'
}

Here I defined two static variables. Each User instance has access to these two variables. Note, that we can initialize it with value;

Instance functions (methods)

var User = function(name, age) {
    this.name = name;
    this.age = age;
}

User.prototype = {
    getName: function() {
        return this.name;
    },

    setName: function(name) {
        this.name = name;
    }
}

Usage example:

var user = new User('Mike', 29);
user.setName('John');
alert(user.getName()); //should be 'John'

Static functions

var User = function(name, age) {
    this.name = name;
    this.age = age;
}

User.create = function(name, age) {
    return new User(name, age);
}

User.prototype = {}

Assuming that by "ctor" you mean "constructor", in JavaScript that's just a function. In this case your constructor would need to be "Object1" itself - in other words, what you've got there makes sense if you have already defined "Object1" to be a function.

Thus,

function Object1(param) {
  // constructor code
}

would be the constructor for your type.

Now there are some JavaScript libraries that provide a utility layer for defining classes. With those, you generally pass some sort of object (like you've got) that includes an "init" function. The libraries provide APIs for creating "classes" and for extending one class from another.

Javascript has prototype based object model. Check this mozilla wiki page and suddenly you'll feel much better in js land.

We can define a constructor in javaScript is same as we fine function, so constructor is just a function.

//function declaration
function func(){}

In case of Contructor We use initial letter in caps in construct like

//constructor 
function Func(){}

now do whatever you want to with your constructor

var constructor1 = new Func();
class CLASS_NAME
{
   private:
         int variable;
   public:
          CLASS_NAME()    //constructor
          {
                 variable = 0;
          }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM