简体   繁体   中英

Why is the var statement omitted when extending Ember.Object?

From the Ember.js documentation :

Person = Ember.Object.extend({
   // [..]
});

It's the first definition of Person , so why is the var statement omitted?


var is also missing in some other places, eg Ember.Application.Create or Ember.StateManager.Create .


Guys, I know what happens when var is omitted. But there doesn't seem to be a good reason to do it, like this it's just confusing people.

It's declared globally so Ember and Handlebars can resolve bindings.

In case of a view for example it's necessary so it can be instantiated in a Handlebars template via the view helper:

Handlebars :

<script type="text/x-handlebars" >
    {{#view MyView}}
         my view's template
    {{/view}}
</script>

JavaScript :​

MyView = Ember.View.extend({});

The following example doesn't work when the controller is declared with a var statement, see http://jsfiddle.net/pangratz666/uzsd6/ :

Handlebars :

<script type="text/x-handlebars" >
    {{controller.name}} - {{secondController.name}}
</script>​

JavaScript :

var controller = Ember.Object.create({
    name: 'my name'
});

var secondController = Ember.Object.create({
    nameBinding: 'controller.name'
});​

If the controllers are declared on a global available object, the App namespace in this case, the the bindings can be resolved, see http://jsfiddle.net/pangratz666/kUmje/ :

Handlebars :

<script type="text/x-handlebars" >
    {{App.controller.name}} - {{App.secondController.name}}
</script>​

JavaScript :

App = Ember.Application.create({});

App.controller = Ember.Object.create({
    name: 'my name'
});

App.secondController = Ember.Object.create({
    nameBinding: 'App.controller.name'
});​

You should take a look at the Emberist 's blog about Naming Conventions in Ember.js .

You only use the var keyword if you want to declare the variable in the local scope. Declaring a variable without var will result in the variable being available in the global scope. This is usually done with classes as you want to access them from anywhere in most cases.

This statement, if not preceded by var Person always creates variable in global scope (window in browser's case), so I guess it's just sloppiness or there may be some reason Person should be global and accessible from anywhere. I agree with @Femaref, this is a pseudo "Class" so it is meant to construct instances like var person = new Person() therefore it should be accesible from other places.

Anyway, it's always a bad habit to pollute the global namespace. The person class should reside in some "namespace hash".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM