How to add static members in EcmaScript 5

I want to add a static function to a class in JavaScript in ExmaScript 5. The definition of my class is as follows:

var Account = {};

Object.defineProperty(Account, 'id', {
    value : null
});

And I would create a new instance like this:

var theAccount = Object.create(Account);
theAccount.id = 123456;

Now I want to add a static function to the class Account. If I created a class Accountusing the constructor function and property prototype, like this:

var Account = function () {
    this.id = null;
};

... I could just do:

Account.instances = {};

Account.createInstance = function () {
    var account = new Account();
    account.id = uuid.v4();
    Account.instances[account.id] = account;
    return account;
};

But since I use Object.defineProperty, not a property prototypeto add members, Account.instancesthey are Account.createInstancealso created when called, Object.createand therefore are instance properties.

How to add a static member to a class when using EcmaScript 5 style object creation?

+5
source share
4

.

var Account = {};

( ​​ ), prototoype. , , :

var Account = {...};
var instances = [];
function createAccount(){...}

, :

var Account = {
    proto: {...},
    instances: [],
    instantiate: function create(){...}
};

... , ? , create - .

Object.create Prototype Chains, create inherit, " " base.


:

Object.create EcmaScript 5?

. new keyword : . Object.create , , ( ).

, . . "Object.create" "" .

+1

, , - . . ( , , ?), defineProperty .

function Account(){
  Object.defineProperty(this, 'id', {
    value: uuid.v4()
  });
  Account.instances[this.id] = this;
}

Account.instances = {};

Account.prototype.id = null;


var account = new Account;
+1

Object.defineProperty, , Account.instances Account.createInstance Object.create , , .

, , - .

    var obj = {};
    obj.static = function() { alert('hello'); }
    var instance = Object.create(obj);
    instance.ownProperty = 'hello';
    alert(!!instance.static); //true - it has .static
    alert(instance.hasOwnProperty('static')); //false - but it not its own
    alert(instance.hasOwnProperty('ownProperty')); //true
+1

ES 5, :

// A static method; this method only 
// exists on the class and doesn't exist 
// on child objects
Person.sayName = function() {
    alert("I am a Person object ;)");  
};

// An instance method; 
// All Person objects will have this method
Person.prototype.setName = function(nameIn) {
    this.name = nameIn;  
}

see @ https://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/

0
source

All Articles