Can I construct a JavaScript object without using the new keyword?

后端 未结 15 2757
北海茫月
北海茫月 2020-11-27 16:04

Here is what I\'d like to do:

function a() {
  // ...
}
function b() {
  //  Some magic, return a new object.
}
var c = b();

c instanceof b // -> true
c          


        
15条回答
  •  渐次进展
    2020-11-27 16:53

    You can use this pattern:

    function SomeConstructor(){
       if (!(this instanceof SomeConstructor)){
            return new SomeConstructor();
       }
       //the constructor properties and methods here
    }
    

    after which you can do:

    var myObj = SomeConstructor();
    

    In addition to this (rather old) answer: you can use a module pattern to create an object:

    function Person(name, age, male) {
      name = name || 'unknown';
      age = age || 0;
      function get() {
        return ['This person is called ', name,
                (!male ? ', her' : ', his'),' age is ',
                age].join('');
      }
      function setAge(nwage) {
         age = nwage;
      }
      return Object.freeze({get: get, setAge: setAge});
    }
    // usage
    var jane =  Person('Jane', 23)
       ,charles = Person('Charles', 32, 1)
       ,mary = Person('Mary', 16);
    
    console.log(jane.get()); //=> This person is called Jane, her age is 23
    mary.setAge(17);
    console.log(mary.get()); //=> This person is called Mary, her age is 17
    

    Here's a jsFiddle for some Date functionallity I created using that pattern.

提交回复
热议问题