最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

oop - JavaScript syntax: what is ({ }) Is it a function or object? - Stack Overflow

programmeradmin7浏览0评论

as a developer with OOP background(c#, Java) OOP JavaScript is wild horse for me. I am trying learn nuts and bolts of language and then jump on libraries (Am I wrong?);

so, I checked dozen of books/tutorials about objects, functions...etc..learned several ways to create objects but syntax used in almost every JS library confuses me. namely

var Person = Backbone.extend.Model({
 //pretty plex staff
 })

what is Model behind the scenes? object? function?

as a developer with OOP background(c#, Java) OOP JavaScript is wild horse for me. I am trying learn nuts and bolts of language and then jump on libraries (Am I wrong?);

so, I checked dozen of books/tutorials about objects, functions...etc..learned several ways to create objects but syntax used in almost every JS library confuses me. namely

var Person = Backbone.extend.Model({
 //pretty plex staff
 })

what is Model behind the scenes? object? function?

Share Improve this question edited Jan 26, 2014 at 2:13 m59 43.8k14 gold badges121 silver badges139 bronze badges asked Jan 26, 2014 at 0:03 brocodebrocode 731 gold badge2 silver badges5 bronze badges 1
  • Shouldn't that be Backbone.Model.extend? – mu is too short Commented Jan 26, 2014 at 0:10
Add a ment  | 

3 Answers 3

Reset to default 14

That is not the correct backbone syntax. That should actually be:

Backbone.Model.extend({

});

In that case, extend is a function. Note that you are invoking it with (). However, functions in javascript are also objects (more on that in a moment). You may be confused about the {} inside of it. That is because you are passing that object as a parameter to the function.

If extend was a function that expected a string as a parameter/argument, it would look like this: extend('some string'). In this case, it is taking an object. For example:

var someObject = {
  someProperty: 'someValue'
}
var Person = Backbone.Model.extend(someObject);

is the same as:

var Person = Backbone.Model.extend({
  someProperty: 'someValue'
});

Here's just a sample of how that might look in the function:

Backbone.Model.extend = function(obj) {
  console.log(obj.someProperty); //logs "someValue"
}

As I said, in javascript, functions are also objects. Actually, most things are objects. I remend you study more on this. As it's not the focus of your question, I'll just briefly demonstrate:

var someObj = {
  someProperty: '123'
};
console.log(someObj.someProperty); //logs "123"

var someFunction = function() {

};
someFunction.someProperty = '123';
console.log(someFunction.someProperty); //logs "123"

Though, it would be better to add to the prototype so that inheritance will work like this:

someFunction.prototype.someProperty = '123';
var foo = new someFunction();
console.log(foo.someProperty); //logs "123"

Here's a little demo you can mess with (click).

So.. in summary, JavaScript is win-sauce.

Are you sure you typed this in correctly? I think you reversed the order of Model and extend. I'm looking at the documentation now, and I see:

Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, puted properties, and access control. You extend Backbone.Model with your domain-specific methods, and Model provides a basic set of functionality for managing changes.

The extend function is implemented in many Javascript libraries: Backbone, Underscore, and jQuery for a few. What it does is to take an object and add methods and instance variables to it. After all in Javascript, objects are simply hashes. This creates an object that has a few methods and data.

var counter = {};
counter.count = 0;
counter.increment = function() {
    this.count++;
}
counter.decrement = function() {
    this.count--;
}

If you want inheritance, you use the object or its constructor's prototype property. The extend method is a way of simulating that. Here's more of the Backbone documentation:

extendBackbone.Model.extend(properties, [classProperties])

To create a Model class of your own, you extend Backbone.Model and provide instance properties, as well as optional classProperties to be attached directly to the constructor function.

extend correctly sets up the prototype chain, so subclasses created with extend can be further extended and subclassed as far as you like.

var Note = Backbone.Model.extend({

    initialize: function() { ... },

    author: function() { ... },

    coordinates: function() { ... },

    allowedToEdit: function(account) {
        return true;
    }

});

In conventional Javascript, you'd write:

function Note() {
    this.initialize  = function() {...};
    this.author      = function() {...};
    this.coordinates = function() {...};
    this.allowedToEdit = function(account) {
        return true;
    };
}

Note.prototype = new Model();  // Inheritance.

Inheritance in JavaScript reminds me of the Perl maxim: There's More than One Way to Do This.

Wele to stackoverflow,

I strongly advise you to have a look at Douglas Crockford's Website and there are also insightfull videos in YUI Theater - start with the ones of Douglas. He's the one who discovered JavaScript has good parts. I also found John Resig's Secrets of the JavaScript Ninja very helpfull for grocking the language (John is the creator of the omnipresent jQuery Library). I would further advise you to look at some libraries (and their code - that's how I learned it - just start with jQuery). There are a ton of other libraries out there but one step at a time :-).

Now to your question: The Backbone.Model is a constructor function, normally you would use it like in Java new Backbone.Model({ configOption: true, ... }). But juicy as JavaScript is it allows you to do crazy things under the hood. For example you can implement your own OOP Class implementation or you can program in a functional style like you would do in Scheme or Lisp. What you see here is Backbone's own subtyping wrapper in action (virtually any decent JS library provides some way to do this). The code is actually doing something along the lines of this:

// Creating a sub type of the Backbone.Model *class* - it's not really 
// a class like in Java or C# but rather a (constructor) function.
var Person = Backbone.Model.extend({ 
    defaults: {
        hasTheOneRing: true
    },
    initialize: function (hasTheOneRing) {
        // Note that Backbone is implementing getters/setters
        // under the hood so you can listen for change events later
        this.set('hasTheOneRing', hasTheOneRing);
    }
    // More configuration ...
});

// Person now is a constructor function that creates instances
// of it's *class* when you create an object with it
var frodo = new Person(true),
    sam = new Person(); // Note that you can supply as many arguments as you wish

// Frodo has the ring
console.log(frodo.get('hasTheOneRing')); 

// Sam doesn't have the ring (well not all the time)
console.log(sam.get('hasTheOneRing')); 

// In plain old JavaScript the sub typing mechanism works a little bit like this:

// A constructor function is just a function
function Person() {
    // JS doesn't have the notion of *super* or *base* but you
    // can emulate the behavior as many libraries do in the wild
    Backbone.Model.call(this);
}

// The prototype of a person is based on that of a Backbone.Model
Person.prototype = Object.create(Backbone.Model.prototype);

// Object.create has not been there since the beginning. After
// Douglas Crockford discovered the good parts this function
// has been adapted into the standard portfolio of every modern browser
// what it does is essentially just:
function create(object) {
    // There's actually more going on in here but you get the idea
    function F() {}
    F.prototype = object;
    return new F();
}

// So this means almost the same
Person.prototype = new Backbone.Model();

My way of getting to love JS was to read library code - and Backbone is open source so have a read and be amazed by the awesomeness g. I think the fact that JS is just plain text send over the wire had a big influence on the language getting that strong in the ecosystem, even Microsoft couldn't stop it.

Give the language a try, when it clicks you'll most likely actually begin to like it :-).

Happy coding!

发布评论

评论列表(0)

  1. 暂无评论