Creating a javascript object with prototyping (no privacy)

后端 未结 4 1772
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-29 01:27

Can I put similar methods in an associative aray like this?

var function_hold = {   
  function1: function(){}
  function2: function (){}
 };

I

相关标签:
4条回答
  • 2021-01-29 01:47

    Yes thats possible and works fine.

    Best Practice syntax would be the Module Pattern

    var outerNamespace = {};
    
    (function(ns) {
       // ns is the local name of the object
       ns.function1 = function() {}
       ns.function2 = function() {}
    
      //self executing anonymous function
    } (outerNamespace));
    
    0 讨论(0)
  • 2021-01-29 01:55

    Yes, that will work fine. You can call the functions with function_hold.function1().

    Note that normally you'll want to associate data with the functions as well:

    var function_hold = {
        x: 0,
        function1: function(){
            this.x++;
        }
        function2: function(){
            alert(this.x);
        }
    };
    
    0 讨论(0)
  • 2021-01-29 01:59

    Yeah, that should would just fine.

    0 讨论(0)
  • 2021-01-29 02:04

    Similarly as you would with any other object-oriented programming language, you group functionality in objects. This works in JavaScript as well.

    Your code actually creates an object. Alternatively you can use JavaScript's prototype mechanism.

    var Person = function(firstname, surname){
        this.firstname = firstname;
        this.surname = surname;
    }
    
    Person.prototype.getFullName = function(){
        return this.firstname + " " + this.surname;
    }
    

    You then call it like

    var tom = new Person("Tom", "Jackwood");
    tom.getFullName();
    
    0 讨论(0)
提交回复
热议问题