开发者

Javascript object definition techniques, pros and cons

开发者 https://www.devze.com 2023-03-10 01:48 出处:网络
What are the basic ways of defining reusable objects in Javascript? I say reusable to exclude singleton techniques, such as declaring a variable with object literal notation directly. I saw somewhere

What are the basic ways of defining reusable objects in Javascript? I say reusable to exclude singleton techniques, such as declaring a variable with object literal notation directly. I saw somewhere that Crockford defines four such ways in his book(s) but I would rather not have to buy a book for this short bit of information.

Here are the ways I'm familiar with:

  • Using this, and constructing with new (I think this is called classical?)

    function Foo() {
        var private = 3;
        this.add = function(bar) { return private + bar; }
    }
    
    var myFoo = new Foo();
    
  • Using prototypes, which is similar

    function Foo() {
        var private = 3;
    }
    Foo.prototype.add = function(bar) { /* 开发者_StackOverflow社区can't access private, correct? */ }
    
  • Returning a literal, not using this or new

    function Foo() {
        var private = 3;
        var add = function(bar) { return private + bar; }
        return {
            add: add
        };
    }
    
    var myFoo = Foo();
    

I can think of relatively minor variations on these that probably don't matter in any significant way. What styles am I missing? More importantly, what are the pros and cons of each? Is there a recommended one to stick to, or is it a matter of preference and a holy war?


Use the prototype. Returning specific objects from constructors makes them non-constructors, and assigning methods to this makes inheritance less convenient.

Returning an object literal

Pros:

  • If a person forgets new, they still get the object.

  • You can create truly private variables, since all methods of the object defined inside the constructor share its scope.

Cons:

  • It’s not a real constructor. Adding something to its prototype won’t change the returned objects, new or no new. new Foo() instanceof Foo would also result in false.

Using prototype

Pros:

  • You leave the constructor uncluttered.

  • This is the standard way of doing things in JavaScript, and all built-in constructors put their methods on their prototypes.

  • Inheritance becomes easier and more correct; you can (and should) use Object.create(ParentConstructor.prototype) instead of new ParentConstructor(), then call ParentConstructor from within Constructor. If you want to override a method, you’re able to do it on the prototype.

  • You can “modify” objects after they’ve already been created.

  • You can extend the prototypes of constructors you don’t have access to.

Cons:

  • It can get to be a bit too verbose, and if you want to change the function’s name, you have to change all of the functions added to the prototype, too. (Either that or define the prototype as one big object literal with a compatible property descriptor for constructor.)

  • They don’t share an instance-specific scope, so you can’t really have private variables.

Assigning to this.* in the constructor

Pros:

  • You can use closures and therefore private member variables.

Cons:

  • No duck typing; you can’t call a method right off of the prototype with any old object. For example, Array.prototype.slice.call(collectionLikeObject).


It's mostly a matter of preference. There's no one way to make Chicken Noodle soup, and uniform objects are the same way.

I don't use any of those 3, although they all work for their own purposes. I use a custom function called Object:deploy, and use it like this..

var a = { hey: 'hello' },
    b = {}.deploy(a);

console.log(b.hey); // 'hello'

Using prototype is the best for most people because of automatic trickling.

function A() {};
A.prototype.hello = "Hey";

var a = new A();
console.log(a.hello); // 'Hey'

A.prototype.hello = "Hello";

console.log(a.hello); // 'Hello'

And contrary to popular belief, you can use private variables in prototype.

function Hello() {};

(function () {
    var greeting = "Hello";

    Hello.prototype.greet = function () { return greeting };
}).apply(this);

But even though that's possible, it's usually better to do..

function Hello() {};
Hello.prototype.greeting = "Hello";
Hello.prototype.greet = function () { return this.greeting };


Well the second approach (prototype) is more similar to standard classes in other languages like Python, in that you have a common "prototype" object which all instances are sharing. To compare the first and second approaches:

  • In approach 1, every time you call "new Foo()", you are creating a brand new object and inserting all the methods. This isn't very time or space efficient, since each Foo instance will have its own table of all the methods. You can test this by creating two Foo objects, and asking foo1.add == foo2.add (false). Approach 3 is very similar to this; I'm not sure what the semantic difference (if any) there is between approaches 1 and 3.
  • In approach 2, you have set up a shared prototype object containing all the methods. If you ask foo1.add == foo2.add, you get true. This is more space- and time-efficient. It also lets you add more methods to the prototype after creating instances, and they will see the new methods.

The problem with approach 2, as you say, is that you can't access the private members. But you can still add non-private members to the object itself, and access those using the prototype methods:

function Foo() {
    this.private = 3;
}
Foo.prototype.add = function(bar) { return this.private + bar }

A caveat is that foo.private is visible externally.


The prototype one doesn't have a per object instance overhead only a per class overhead for the add function. This alone is the reason why I don't like the other two approaches.


Do not forget about inheritance. Some day you'll need. And for organizing inheritance the best approach is combined technic:

function Foo() {
    this.array = [1, 2, 3];
    this.add = function(bar) { return private + bar; }
}

Foo.prototype.add = function(bar) {  }

var myFoo = new Foo();

Setting fields in constructor is useful to avoid modifying them by children objects. Setting methods to prototype is faster then doing this every time in constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消