开发者

Why/How should I used objects in JavaScript?

I understand how to instantiate objects and call them, but I just cannot find a reason to use them in my script. I could do

var obj = {
    hi: function() {
        return "Hello";
    }
}; 

but why can't I just do it the same way like:

function hi() {
    return "Hello";
}

I've never understood the reasons why I should use prototyping either. Most of the things I do in JavaScript开发者_如何学C I can do well without objects. But I want to use objects. What are objects for and what are the reasons why I should use them?


Objects are useful for example for making a single unit out of values that belong together. Example:

function Person(firstName, lastName, gender, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.gender = gender;
  this.age = age;
}

Person.prototype = {
  getFullName: function() { return this.firstName + ' ' + this.lastName; },
  isMale: function() { return this.gender == 'Male'; },
  isFemale: function() { return this.gender == 'Female'; }
};

var amanda = new Person('Amanda', 'Smith', "Female", 42);
var john = new Person('John', 'Doe', 'Male', 72);

alert(amanda.getFullName());
alert(john.isMale());

Compared to the less structured:

function getFullName(firstName, lastName) {
  return firstName + ' ' + lastName;
}

function isMale(gender) {
  return gender == 'Male';
}

function isFemale(gender) {
  return gender == 'Female';
}

var amandaFirstName = 'Amanda';
var amandaLastName = 'Smith';
var amandaGender = 'Female';
var amandaAge = 42;
var johnFirstName = 'John';
var johnLastName = 'Doe';
var johnGender = 'Male';
var johnAge = 72;

alert(getFullName(amandaFirstName, amandaLastName));
alert(isMale(johnGender));


Objects are useful because

  1. They are stateful.
  2. They can store relations between strings and data.
  3. It can be easier to decompose a problem by breaking it up into objects that collect related operations and state.

If you don't need non-global state, have no need of lookup tables, and your problem is small or more easily decomposed functionally then don't use objects.


Without what you are referring to as objects, you are going to have loose functions all over the place. This very often will result in code that is very difficult to maintain. At a bare minimum objects give you the ability to lump functions together in order to simulate namespaces-- and that's at a bare minimum.


In your simple example, it makes indeed no sense to write a semi "class" / object to hold that method. But when your code grows, you're getting more and more functions and methods, you don't really want to have them all in one big (global) namespace. That is just so impossible to maintenain, no one will understand that code including you at some later point.

That is the first good reason to wrap methods together in an object/"class". Another good reason is re-usabilty. If you're writting objects which are able to inherit their methods, you can re-create another object and abstract it from there on. Most simple concept, but you want to use it if you're describing "things" in your application as module/object.


It tries to simulate the OOP paradigm that's all. There are various ways of doing this. But ask yourself, doe 'hi' belong in 'obj' or can it be a standalone function? Its all about how closely related is the function to the object. Does the function needs to access the objects private variables and such?


This is less of a "objects in Javascript" and more of an objects in general" question.

I'd say the most relevant Javascript The only thing Javascript specific about objects is their neat use when namespacing. For example, most Javascript libraries pack all their stuff in a single object to avoid namespace collision:

dojo.create( ... )
dojo.connect( ... )

As for the other questions of why OOP, there are 2 basic things I think OOP excels at (generic, dumb, examples follow):

  1. Dynamic dispatching - get rid of "ifs" and put responsabilitty where it belongs

    When you look at a code that has tons of "switchs":

    function doStuff(animal){
        if animal is a tiger:
            print_tiger_roar();
       else if animal is a cow
            print_cow_moo();
    
       if animal is a tiger:
            print_tiger_wants_meat();
       else if animal is a cow
            print cow_wants_grass();
    

    It might be a good idea to bundle each different kind of behaviour in a different kind of object and use dynamic dispatching instead:

    function doStuff(animal):
       animal.print_speak();
       animal.print_food_type();
    

    Now, if you come up with another kind of animal in the future, you don't need to go looking around your code to add it - all you need to do is create a new class with the appropriate print_speack and print_food_type methods and the rest of the code won't notice a thing.

  2. Inheritance + reusing methods

    In a normal OO language each object stores (and spends memory) for its instance variables, while all methods + static variables are stored in a single place by the class. Javascript doesn't have classes, but it has prototypes and they serve the same basic function in the end.


Some generic thoughts concerning "Why" part:

Objects exist to communicate. It is a common vocabulary for everyone involved in a project. People are used to operate with things (objects) and their operations (messages or methods), rather than just with disconnected actions (functions).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜