Search Results

Search found 13794 results on 552 pages for 'variable scope'.

Page 1/552 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • JavaScript: Reference a functions local scope as an object

    - by eBusiness
    When I call a function, a local scope is erected for that call. Is there any way to directly reference that scope as an object? Just like window is a reference for the global scope object. Example: function test(foo){ var bar=1 //Now, can I access the object containing foo, bar, arguments and anything //else within the local scope like this: magicIdentifier.bar } Alternately, does anyone have a complete list of what is in the global scope on top of custom variables? Background: I'm trying to get down to a way of completely shifting to global scope from within a function call, the with statement is a joke, call works a little better, but it still breaks for anything declared in function scope but not in global scope, therefore I would declare these few cases in global scope, but that requires me to know what they are. The IE function execScript makes a complete shift, but that only solves the problem for IE. Note: To anyone loading JavaScript dynamically, setTimeout(code,1) is a simple effective hack to achieve global scope, but it will not execute immediately.

    Read the article

  • Misunderstanding Scope in JavaScript?

    - by Jeff
    I've seen a few other developers talk about binding scope in JavaScript but it has always seemed to me like this is an inaccurate phrase. The Function.prototype.call and Function.prototype.apply don't pass scope around between two methods; they change the caller of the function - two very different things. For example: function outer() { var item = { foo: 'foo' }; var bar = 'bar'; inner.apply(item, null); } function inner() { console.log(this.foo); //foo console.log(bar); //ReferenceError: bar is not defined } If the scope of outer was really passed into inner, I would expect that inner would be able to access bar, but it can't. bar was in scope in outer and it is out of scope in inner. Hence, the scope wasn't passed. Even the Mozilla docs don't mention anything about passing scope: Calls a function with a given this value and arguments provided as an array. Am I misunderstanding scope or specifically scope as it applies to JavaScript? Or is it these other developers that are misunderstanding it?

    Read the article

  • MooTools/JavaScript variable scope

    - by 827
    I am trying to make each number displayed clickable. "1" should alert() 80, "2" should produce 60, etc. However, when the alert(adjust) is called, it only shows 0, not the correct numbers. However, if the commented out alert(adjust) is uncommented, it produces the correct number on page load, but not on clicking. I was wondering why the code inside addEvents cannot access the previously defined variable adjust. <html> <head> <script type="text/javascript" charset="utf-8" src="mootools.js"></script> <script type="text/javascript" charset="utf-8"> window.addEvent('domready', function() { var id_numbers = [1,2,3,4,5]; for(var i = 0; i<id_numbers.length; i++) { var adjust = (20 * (5 - id_numbers[i])); // alert(adjust); $('i_' + id_numbers[i]).addEvents({ 'click': function() { alert(adjust); } }); } }); </script> </head> <body> <div id="i_1">1</div> <div id="i_2">2</div> <div id="i_3">3</div> <div id="i_4">4</div> <div id="i_5">5</div> </body> </html> Thanks.

    Read the article

  • What is meant by Scope of a variable?

    - by Appy
    I think of the scope of a variable as - "The scope of a particular variable is the range within a program's source code in which that variable is recognized by the compiler". That statement is from "Scope and Lifetime of Variables in C++", which I read many months ago. Recently I came across this in LeMoyne-Owen College courses: What exactly is the difference between the scope of variables in C# and (C99, C++, Java) when However a variable still must be declared before it can be used

    Read the article

  • AngularJS on top of ASP.NET: Moving the MVC framework out to the browser

    - by Varun Chatterji
    Heavily drawing inspiration from Ruby on Rails, MVC4’s convention over configuration model of development soon became the Holy Grail of .NET web development. The MVC model brought with it the goodness of proper separation of concerns between business logic, data, and the presentation logic. However, the MVC paradigm, was still one in which server side .NET code could be mixed with presentation code. The Razor templating engine, though cleaner than its predecessors, still encouraged and allowed you to mix .NET server side code with presentation logic. Thus, for example, if the developer required a certain <div> tag to be shown if a particular variable ShowDiv was true in the View’s model, the code could look like the following: Fig 1: To show a div or not. Server side .NET code is used in the View Mixing .NET code with HTML in views can soon get very messy. Wouldn’t it be nice if the presentation layer (HTML) could be pure HTML? Also, in the ASP.NET MVC model, some of the business logic invariably resides in the controller. It is tempting to use an anti­pattern like the one shown above to control whether a div should be shown or not. However, best practice would indicate that the Controller should not be aware of the div. The ShowDiv variable in the model should not exist. A controller should ideally, only be used to do the plumbing of getting the data populated in the model and nothing else. The view (ideally pure HTML) should render the presentation layer based on the model. In this article we will see how Angular JS, a new JavaScript framework by Google can be used effectively to build web applications where: 1. Views are pure HTML 2. Controllers (in the server sense) are pure REST based API calls 3. The presentation layer is loaded as needed from partial HTML only files. What is MVVM? MVVM short for Model View View Model is a new paradigm in web development. In this paradigm, the Model and View stuff exists on the client side through javascript instead of being processed on the server through postbacks. These frameworks are JavaScript frameworks that facilitate the clear separation of the “frontend” or the data rendering logic from the “backend” which is typically just a REST based API that loads and processes data through a resource model. The frameworks are called MVVM as a change to the Model (through javascript) gets reflected in the view immediately i.e. Model > View. Also, a change on the view (through manual input) gets reflected in the model immediately i.e. View > Model. The following figure shows this conceptually (comments are shown in red): Fig 2: Demonstration of MVVM in action In Fig 2, two text boxes are bound to the same variable model.myInt. Thus, changing the view manually (changing one text box through keyboard input) also changes the other textbox in real time demonstrating V > M property of a MVVM framework. Furthermore, clicking the button adds 1 to the value of model.myInt thus changing the model through JavaScript. This immediately updates the view (the value in the two textboxes) thus demonstrating the M > V property of a MVVM framework. Thus we see that the model in a MVVM JavaScript framework can be regarded as “the single source of truth“. This is an important concept. Angular is one such MVVM framework. We shall use it to build a simple app that sends SMS messages to a particular number. Application, Routes, Views, Controllers, Scope and Models Angular can be used in many ways to construct web applications. For this article, we shall only focus on building Single Page Applications (SPAs). Many of the approaches we will follow in this article have alternatives. It is beyond the scope of this article to explain every nuance in detail but we shall try to touch upon the basic concepts and end up with a working application that can be used to send SMS messages using Sent.ly Plus (a service that is itself built using Angular). Before you read on, we would like to urge you to forget what you know about Models, Views, Controllers and Routes in the ASP.NET MVC4 framework. All these words have different meanings in the Angular world. Whenever these words are used in this article, they will refer to Angular concepts and not ASP.NET MVC4 concepts. The following figure shows the skeleton of the root page of an SPA: Fig 3: The skeleton of a SPA The skeleton of the application is based on the Bootstrap starter template which can be found at: http://getbootstrap.com/examples/starter­template/ Apart from loading the Angular, jQuery and Bootstrap JavaScript libraries, it also loads our custom scripts /app/js/controllers.js /app/js/app.js These scripts define the routes, views and controllers which we shall come to in a moment. Application Notice that the body tag (Fig. 3) has an extra attribute: ng­app=”smsApp” Providing this tag “bootstraps” our single page application. It tells Angular to load a “module” called smsApp. This “module” is defined /app/js/app.js angular.module('smsApp', ['smsApp.controllers', function () {}]) Fig 4: The definition of our application module The line shows above, declares a module called smsApp. It also declares that this module “depends” on another module called “smsApp.controllers”. The smsApp.controllers module will contain all the controllers for our SPA. Routing and Views Notice that in the Navbar (in Fig 3) we have included two hyperlinks to: “#/app” “#/help” This is how Angular handles routing. Since the URLs start with “#”, they are actually just bookmarks (and not server side resources). However, our route definition (in /app/js/app.js) gives these URLs a special meaning within the Angular framework. angular.module('smsApp', ['smsApp.controllers', function () { }]) //Configure the routes .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/binding', { templateUrl: '/app/partials/bindingexample.html', controller: 'BindingController' }); }]); Fig 5: The definition of a route with an associated partial view and controller As we can see from the previous code sample, we are using the $routeProvider object in the configuration of our smsApp module. Notice how the code “asks for” the $routeProvider object by specifying it as a dependency in the [] braces and then defining a function that accepts it as a parameter. This is known as dependency injection. Please refer to the following link if you want to delve into this topic: http://docs.angularjs.org/guide/di What the above code snippet is doing is that it is telling Angular that when the URL is “#/binding”, then it should load the HTML snippet (“partial view”) found at /app/partials/bindingexample.html. Also, for this URL, Angular should load the controller called “BindingController”. We have also marked the div with the class “container” (in Fig 3) with the ng­view attribute. This attribute tells Angular that views (partial HTML pages) defined in the routes will be loaded within this div. You can see that the Angular JavaScript framework, unlike many other frameworks, works purely by extending HTML tags and attributes. It also allows you to extend HTML with your own tags and attributes (through directives) if you so desire, you can find out more about directives at the following URL: http://www.codeproject.com/Articles/607873/Extending­HTML­with­AngularJS­Directives Controllers and Models We have seen how we define what views and controllers should be loaded for a particular route. Let us now consider how controllers are defined. Our controllers are defined in the file /app/js/controllers.js. The following snippet shows the definition of the “BindingController” which is loaded when we hit the URL http://localhost:port/index.html#/binding (as we have defined in the route earlier as shown in Fig 5). Remember that we had defined that our application module “smsApp” depends on the “smsApp.controllers” module (see Fig 4). The code snippet below shows how the “BindingController” defined in the route shown in Fig 5 is defined in the module smsApp.controllers: angular.module('smsApp.controllers', [function () { }]) .controller('BindingController', ['$scope', function ($scope) { $scope.model = {}; $scope.model.myInt = 6; $scope.addOne = function () { $scope.model.myInt++; } }]); Fig 6: The definition of a controller in the “smsApp.controllers” module. The pieces are falling in place! Remember Fig.2? That was the code of a partial view that was loaded within the container div of the skeleton SPA shown in Fig 3. The route definition shown in Fig 5 also defined that the controller called “BindingController” (shown in Fig 6.) was loaded when we loaded the URL: http://localhost:22544/index.html#/binding The button in Fig 2 was marked with the attribute ng­click=”addOne()” which added 1 to the value of model.myInt. In Fig 6, we can see that this function is actually defined in the “BindingController”. Scope We can see from Fig 6, that in the definition of “BindingController”, we defined a dependency on $scope and then, as usual, defined a function which “asks for” $scope as per the dependency injection pattern. So what is $scope? Any guesses? As you might have guessed a scope is a particular “address space” where variables and functions may be defined. This has a similar meaning to scope in a programming language like C#. Model: The Scope is not the Model It is tempting to assign variables in the scope directly. For example, we could have defined myInt as $scope.myInt = 6 in Fig 6 instead of $scope.model.myInt = 6. The reason why this is a bad idea is that scope in hierarchical in Angular. Thus if we were to define a controller which was defined within the another controller (nested controllers), then the inner controller would inherit the scope of the parent controller. This inheritance would follow JavaScript prototypal inheritance. Let’s say the parent controller defined a variable through $scope.myInt = 6. The child controller would inherit the scope through java prototypical inheritance. This basically means that the child scope has a variable myInt that points to the parent scopes myInt variable. Now if we assigned the value of myInt in the parent, the child scope would be updated with the same value as the child scope’s myInt variable points to the parent scope’s myInt variable. However, if we were to assign the value of the myInt variable in the child scope, then the link of that variable to the parent scope would be broken as the variable myInt in the child scope now points to the value 6 and not to the parent scope’s myInt variable. But, if we defined a variable model in the parent scope, then the child scope will also have a variable model that points to the model variable in the parent scope. Updating the value of $scope.model.myInt in the parent scope would change the model variable in the child scope too as the variable is pointed to the model variable in the parent scope. Now changing the value of $scope.model.myInt in the child scope would ALSO change the value in the parent scope. This is because the model reference in the child scope is pointed to the scope variable in the parent. We did no new assignment to the model variable in the child scope. We only changed an attribute of the model variable. Since the model variable (in the child scope) points to the model variable in the parent scope, we have successfully changed the value of myInt in the parent scope. Thus the value of $scope.model.myInt in the parent scope becomes the “single source of truth“. This is a tricky concept, thus it is considered good practice to NOT use scope inheritance. More info on prototypal inheritance in Angular can be found in the “JavaScript Prototypal Inheritance” section at the following URL: https://github.com/angular/angular.js/wiki/Understanding­Scopes. Building It: An Angular JS application using a .NET Web API Backend Now that we have a perspective on the basic components of an MVVM application built using Angular, let’s build something useful. We will build an application that can be used to send out SMS messages to a given phone number. The following diagram describes the architecture of the application we are going to build: Fig 7: Broad application architecture We are going to add an HTML Partial to our project. This partial will contain the form fields that will accept the phone number and message that needs to be sent as an SMS. It will also display all the messages that have previously been sent. All the executable code that is run on the occurrence of events (button clicks etc.) in the view resides in the controller. The controller interacts with the ASP.NET WebAPI to get a history of SMS messages, add a message etc. through a REST based API. For the purposes of simplicity, we will use an in memory data structure for the purposes of creating this application. Thus, the tasks ahead of us are: Creating the REST WebApi with GET, PUT, POST, DELETE methods. Creating the SmsView.html partial Creating the SmsController controller with methods that are called from the SmsView.html partial Add a new route that loads the controller and the partial. 1. Creating the REST WebAPI This is a simple task that should be quite straightforward to any .NET developer. The following listing shows our ApiController: public class SmsMessage { public string to { get; set; } public string message { get; set; } } public class SmsResource : SmsMessage { public int smsId { get; set; } } public class SmsResourceController : ApiController { public static Dictionary<int, SmsResource> messages = new Dictionary<int, SmsResource>(); public static int currentId = 0; // GET api/<controller> public List<SmsResource> Get() { List<SmsResource> result = new List<SmsResource>(); foreach (int key in messages.Keys) { result.Add(messages[key]); } return result; } // GET api/<controller>/5 public SmsResource Get(int id) { if (messages.ContainsKey(id)) return messages[id]; return null; } // POST api/<controller> public List<SmsResource> Post([FromBody] SmsMessage value) { //Synchronize on messages so we don't have id collisions lock (messages) { SmsResource res = (SmsResource) value; res.smsId = currentId++; messages.Add(res.smsId, res); //SentlyPlusSmsSender.SendMessage(value.to, value.message); return Get(); } } // PUT api/<controller>/5 public List<SmsResource> Put(int id, [FromBody] SmsMessage value) { //Synchronize on messages so we don't have id collisions lock (messages) { if (messages.ContainsKey(id)) { //Update the message messages[id].message = value.message; messages[id].to = value.message; } return Get(); } } // DELETE api/<controller>/5 public List<SmsResource> Delete(int id) { if (messages.ContainsKey(id)) { messages.Remove(id); } return Get(); } } Once this class is defined, we should be able to access the WebAPI by a simple GET request using the browser: http://localhost:port/api/SmsResource Notice the commented line: //SentlyPlusSmsSender.SendMessage The SentlyPlusSmsSender class is defined in the attached solution. We have shown this line as commented as we want to explain the core Angular concepts. If you load the attached solution, this line is uncommented in the source and an actual SMS will be sent! By default, the API returns XML. For consumption of the API in Angular, we would like it to return JSON. To change the default to JSON, we make the following change to WebApiConfig.cs file located in the App_Start folder. public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); var appXmlType = config.Formatters.XmlFormatter. SupportedMediaTypes. FirstOrDefault( t => t.MediaType == "application/xml"); config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); } } We now have our backend REST Api which we can consume from Angular! 2. Creating the SmsView.html partial This simple partial will define two fields: the destination phone number (international format starting with a +) and the message. These fields will be bound to model.phoneNumber and model.message. We will also add a button that we shall hook up to sendMessage() in the controller. A list of all previously sent messages (bound to model.allMessages) will also be displayed below the form input. The following code shows the code for the partial: <!--­­ If model.errorMessage is defined, then render the error div -­­> <div class="alert alert-­danger alert-­dismissable" style="margin­-top: 30px;" ng­-show="model.errorMessage != undefined"> <button type="button" class="close" data­dismiss="alert" aria­hidden="true">&times;</button> <strong>Error!</strong> <br /> {{ model.errorMessage }} </div> <!--­­ The input fields bound to the model --­­> <div class="well" style="margin-­top: 30px;"> <table style="width: 100%;"> <tr> <td style="width: 45%; text-­align: center;"> <input type="text" placeholder="Phone number (eg; +44 7778 609466)" ng­-model="model.phoneNumber" class="form-­control" style="width: 90%" onkeypress="return checkPhoneInput();" /> </td> <td style="width: 45%; text-­align: center;"> <input type="text" placeholder="Message" ng­-model="model.message" class="form-­control" style="width: 90%" /> </td> <td style="text-­align: center;"> <button class="btn btn-­danger" ng-­click="sendMessage();" ng-­disabled="model.isAjaxInProgress" style="margin­right: 5px;">Send</button> <img src="/Content/ajax-­loader.gif" ng­-show="model.isAjaxInProgress" /> </td> </tr> </table> </div> <!--­­ The past messages ­­--> <div style="margin-­top: 30px;"> <!­­-- The following div is shown if there are no past messages --­­> <div ng­-show="model.allMessages.length == 0"> No messages have been sent yet! </div> <!--­­ The following div is shown if there are some past messages --­­> <div ng-­show="model.allMessages.length == 0"> <table style="width: 100%;" class="table table-­striped"> <tr> <td>Phone Number</td> <td>Message</td> <td></td> </tr> <!--­­ The ng-­repeat directive is line the repeater control in .NET, but as you can see this partial is pure HTML which is much cleaner --> <tr ng-­repeat="message in model.allMessages"> <td>{{ message.to }}</td> <td>{{ message.message }}</td> <td> <button class="btn btn-­danger" ng-­click="delete(message.smsId);" ng­-disabled="model.isAjaxInProgress">Delete</button> </td> </tr> </table> </div> </div> The above code is commented and should be self explanatory. Conditional rendering is achieved through using the ng-­show=”condition” attribute on various div tags. Input fields are bound to the model and the send button is bound to the sendMessage() function in the controller as through the ng­click=”sendMessage()” attribute defined on the button tag. While AJAX calls are taking place, the controller sets model.isAjaxInProgress to true. Based on this variable, buttons are disabled through the ng-­disabled directive which is added as an attribute to the buttons. The ng-­repeat directive added as an attribute to the tr tag causes the table row to be rendered multiple times much like an ASP.NET repeater. 3. Creating the SmsController controller The penultimate piece of our application is the controller which responds to events from our view and interacts with our MVC4 REST WebAPI. The following listing shows the code we need to add to /app/js/controllers.js. Note that controller definitions can be chained. Also note that this controller “asks for” the $http service. The $http service is a simple way in Angular to do AJAX. So far we have only encountered modules, controllers, views and directives in Angular. The $http is new entity in Angular called a service. More information on Angular services can be found at the following URL: http://docs.angularjs.org/guide/dev_guide.services.understanding_services. .controller('SmsController', ['$scope', '$http', function ($scope, $http) { //We define the model $scope.model = {}; //We define the allMessages array in the model //that will contain all the messages sent so far $scope.model.allMessages = []; //The error if any $scope.model.errorMessage = undefined; //We initially load data so set the isAjaxInProgress = true; $scope.model.isAjaxInProgress = true; //Load all the messages $http({ url: '/api/smsresource', method: "GET" }). success(function (data, status, headers, config) { this callback will be called asynchronously //when the response is available $scope.model.allMessages = data; //We are done with AJAX loading $scope.model.isAjaxInProgress = false; }). error(function (data, status, headers, config) { //called asynchronously if an error occurs //or server returns response with an error status. $scope.model.errorMessage = "Error occurred status:" + status; //We are done with AJAX loading $scope.model.isAjaxInProgress = false; }); $scope.delete = function (id) { //We are making an ajax call so we set this to true $scope.model.isAjaxInProgress = true; $http({ url: '/api/smsresource/' + id, method: "DELETE" }). success(function (data, status, headers, config) { // this callback will be called asynchronously // when the response is available $scope.model.allMessages = data; //We are done with AJAX loading $scope.model.isAjaxInProgress = false; }); error(function (data, status, headers, config) { // called asynchronously if an error occurs // or server returns response with an error status. $scope.model.errorMessage = "Error occurred status:" + status; //We are done with AJAX loading $scope.model.isAjaxInProgress = false; }); } $scope.sendMessage = function () { $scope.model.errorMessage = undefined; var message = ''; if($scope.model.message != undefined) message = $scope.model.message.trim(); if ($scope.model.phoneNumber == undefined || $scope.model.phoneNumber == '' || $scope.model.phoneNumber.length < 10 || $scope.model.phoneNumber[0] != '+') { $scope.model.errorMessage = "You must enter a valid phone number in international format. Eg: +44 7778 609466"; return; } if (message.length == 0) { $scope.model.errorMessage = "You must specify a message!"; return; } //We are making an ajax call so we set this to true $scope.model.isAjaxInProgress = true; $http({ url: '/api/smsresource', method: "POST", data: { to: $scope.model.phoneNumber, message: $scope.model.message } }). success(function (data, status, headers, config) { // this callback will be called asynchronously // when the response is available $scope.model.allMessages = data; //We are done with AJAX loading $scope.model.isAjaxInProgress = false; }). error(function (data, status, headers, config) { // called asynchronously if an error occurs // or server returns response with an error status. $scope.model.errorMessage = "Error occurred status:" + status // We are done with AJAX loading $scope.model.isAjaxInProgress = false; }); } }]); We can see from the previous listing how the functions that are called from the view are defined in the controller. It should also be evident how easy it is to make AJAX calls to consume our MVC4 REST WebAPI. Now we are left with the final piece. We need to define a route that associates a particular path with the view we have defined and the controller we have defined. 4. Add a new route that loads the controller and the partial This is the easiest part of the puzzle. We simply define another route in the /app/js/app.js file: $routeProvider.when('/sms', { templateUrl: '/app/partials/smsview.html', controller: 'SmsController' }); Conclusion In this article we have seen how much of the server side functionality in the MVC4 framework can be moved to the browser thus delivering a snappy and fast user interface. We have seen how we can build client side HTML only views that avoid the messy syntax offered by server side Razor views. We have built a functioning app from the ground up. The significant advantage of this approach to building web apps is that the front end can be completely platform independent. Even though we used ASP.NET to create our REST API, we could just easily have used any other language such as Node.js, Ruby etc without changing a single line of our front end code. Angular is a rich framework and we have only touched on basic functionality required to create a SPA. For readers who wish to delve further into the Angular framework, we would recommend the following URL as a starting point: http://docs.angularjs.org/misc/started. To get started with the code for this project: Sign up for an account at http://plus.sent.ly (free) Add your phone number Go to the “My Identies Page” Note Down your Sender ID, Consumer Key and Consumer Secret Download the code for this article at: https://docs.google.com/file/d/0BzjEWqSE31yoZjZlV0d0R2Y3eW8/edit?usp=sharing Change the values of Sender Id, Consumer Key and Consumer Secret in the web.config file Run the project through Visual Studio!

    Read the article

  • Class scope variable vs method scope variable

    - by Masud
    I know that variable scope is enclosed by a start of block { and an end of block }. If the same variable is declared within the block, then the compile error Variable already defined occurs. But take a look at following example. public class Test{ int x=0;// Class scope variable public void m(){ int x=9; //redeclaration of x is valid within the scope of same x. if(true){ int x=7; // but this redeclaration generates a compile time error. } } Here, x can be redeclared in a method, although it's already declared in the class. But in the if block, x can't be redeclared. Why is it that redeclaration of a class scope variable doesn't generate an error, but a method scope variable redeclaration generates an error?

    Read the article

  • Isn't class scope purely for organization?

    - by Di-0xide
    Isn't scope just a way to organize classes, preventing outside code from accessing certain things you don't want accessed? More specifically, is there any functional gain to having public, protected, or private-scoped methods? Is there any advantage to classifying method/property scope rather than to, say, just public-ize everything? My presumption says no simply because, in binary code, there is no sense of scope (other than r/w/e, which isn't really scope at all, but rather global permissions for a block of memory). Is this correct? What about in languages like Java and C#[.NET]?

    Read the article

  • In C++, what is the scope resolution ("order of precedence") for shadowed variable names?

    - by Emile Cormier
    In C++, what is the scope resolution ("order of precedence") for shadowed variable names? I can't seem to find a concise answer online. For example: #include <iostream> int shadowed = 1; struct Foo { Foo() : shadowed(2) {} void bar(int shadowed = 3) { std::cout << shadowed << std::endl; // What does this output? { int shadowed = 4; std::cout << shadowed << std::endl; // What does this output? } } int shadowed; }; int main() { Foo().bar(); } I can't think of any other scopes where a variable might conflict. Please let me know if I missed one. What is the order of priority for all four shadow variables when inside the bar member function?

    Read the article

  • Scientific evidence that supports using long variable names instead of abbreviations?

    - by Sebastian Dietz
    Is there any scientific evidence that the human brain can read and understand fully written variable names better/faster than abbreviated ones? Like PersistenceManager persistenceManager; in contrast to PersistenceManager pm; I have the impression that I get a better grasp of code that does not use abbreviations, even if the abbreviations would have been commonly used throughout the codebase. Can this individual feeling be backed up by any studies?

    Read the article

  • Can't add object to Array in jQuery's getJSON data function (scope issue)

    - by seo20
    I have a person object and wants to store it into a global ArrayCollection I have made. Works great in normal scope: var s = new ArrayCollection(); s.add(new person("Knud", "Mikkelsen", 35)); The problem is when I want to add people inside my jQuery function "mainFunction". I can't seem to get it right. I know it's something to do with scope and I have to wrap something in functions like in my ArrayCollection. Please help me - thanks a lot. function ArrayCollection() { var myArray = new Array; return { empty: function () { myArray.splice(0, myArray.length); }, add: function (myElement) { myArray.push(myElement); }, getAll: function () { return myArray; } } } function person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = parseInt(parseFloat(age)); } function mainFunction() { //.... var s = new ArrayCollection(); s.add(new person("Knud", "Mikkelsen", 35)); $.getJSON(url, function (data) { for (var x = 0; x < data.length; x++) { var myPerson = new person(data[x].FirstName.toString(), data[x].LastName.toString(), data[x].Age.toString()); s.add(myPerson); } }); alert(drawArray(s.getAll())); } function drawArray(myArray) { var v = ""; for (var i = 0; i < myArray.length; i++) { v += myArray[i].firstName + " " + myArray[i].lastName + " (" + myArray[i].age + ")\n"; } return v; }

    Read the article

  • Changing a Variable Out of Scope?

    - by Matrym
    Is there any way to change a variable while out of scope? I know in general, you cannot, but I'm wondering if there are any tricks or overrides. For example, is there any way to make the following work: function blah(){ var a = 1 } a = 2; alert(blah());

    Read the article

  • C# Anonymous method variable scope problem with IEnumerable<T>

    - by PaN1C_Showt1Me
    Hi. I'm trying to iterate through all components and for those who implements ISupportsOpen allow to open a project. The problem is when the anonymous method is called, then the component variable is always the same element (as coming from the outer scope from IEnumerable) foreach (ISupportsOpen component in something.Site.Container.Components.OfType<ISupportsOpen>()) { MyClass m = new MyClass(); m.Called += new EventHandler(delegate(object sender, EventArgs e) { if (component.CanOpenProject(..)) component.OpenProject(..); }); itemsList.Add(m); } How should it be solved, please?

    Read the article

  • How to structure javascript callback so that function scope is maintained properly

    - by Chetan
    I'm using XMLHttpRequest, and I want to access a local variable in the success callback function. Here is the code: function getFileContents(filePath, callbackFn) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { callbackFn(xhr.responseText); } } xhr.open("GET", chrome.extension.getURL(filePath), true); xhr.send(); } And I want to call it like this: var test = "lol"; getFileContents("hello.js", function(data) { alert(test); }); Here, test would be out of the scope of the callback function, since only the enclosing function's variables are accessible inside the callback function. What is the best way to pass test to the callback function so the alert(test); will display test correctly?

    Read the article

  • c++ function scope

    - by Myx
    I have a main function in A.cpp which has the following relevant two lines of code: B definition(input_file); definition.Print(); In B.h I have the following relevant lines of code: class B { public: // Constructors B(void); B(const char *filename); ~B(void); // File input int ParseLSFile(const char *filename); // Debugging void Print(void); // Data int var1; double var2; vector<char* > var3; map<char*, vector<char* > > var4; } In B.cpp, I have the following function signatures (sorry for being redundant): B::B(void) : var1(-1), var2(numeric_limits<double>::infinity()) { } B::B(const char *filename) { B *def = new B(); def->ParseLSFile(filename); } B::~B(void) { // Free memory for var3 and var 4 } int B::ParseLSFile(const char *filename) { // assign var1, var2, var3, and var4 values } void B::Print(void) { // print contents of var1, var2, var3, and var4 to stdout } So when I call Print() from within B::ParseLSFile(...), then the contents of my structures print correctly to stdout. However, when I call definition.Print() from A.cpp, my structures are empty or contain garbage. Can anyone recommend the correct way to initialize/pass my structures so that I can access them outside of the scope of my function definition? Thanks.

    Read the article

  • PHP Scope Resolution Operator Question

    - by anthony
    I'm having trouble with the MyClass::function(); style of calling methods and can't figure out why. Here's an example (I'm using Kohana framework btw): class Test_Core { public $var1 = "lots of testing"; public function output() { $print_out = $this->var1; echo $print_out; } } I try to use the following to call it, but it returns $var1 as undefined: Test::output() However, this works fine: $test = new Test(); $test->output(); I generally use this style of calling objects as opposed to the "new Class" style, but I can't figure out why it doesn't want to work.

    Read the article

  • Property Scope (Iphone)

    - by Hank
    Hello All. I am having trouble accessing a declared property and I think I am missing something fundamental about the nature of properties and perhaps view controllers. Here's what I'm doing so far: declaring a property "myPhone" in a root view controller called RootViewController. grabbing a phone number from a modally presented people picker setting "myPhone" to the value from the people picker (from within shouldContinueAfterSelectingPerson of ABPeoplePickerNavigationController) trying to access "myPhone" from another modally presented view controller "myPhone" continues to NSLog to null despite trying every permutation of self.myPhone, super, RootViewController, etc. to try and access the value I set. What am I missing?

    Read the article

  • How to add a specific method to a particular scope in Visual Studion 2005

    - by pragadheesh
    Hi, In my visual studio project (C++), when i copy a method(meth1) of a particular scope say 'scope1' and paste it in the same code area, it is getting pasted in General Scope. i.e I want to add a method into a particular scope but when i try it is getting added in general scope. How can i solve this? For eg: There is an existing method: void add(int a, int b) { .... } This method is in File scope. i.e limited for that file. Now i want to add another method add2 in the same file scope. So I copied the existing add method and pasted it. void add2(int a, int b) { .... } But this method is getting added in the global scope and not in the file scope.

    Read the article

  • Should I sacrifice code succintness to ensure the narrowest variable scope? [duplicate]

    - by David Scholefield
    This question already has an answer here: Is the usage of internal scope blocks within a function bad style? 3 answers In many languages (e.g. both Perl and Java - which are the two languages I work most with) it is possible to narrow the scope of local variables by declaring them within a block. Although it adds extra code length (the opening and closing block braces), and possibly reduces readability, should I create blocks purely to narrow the scope of variables to the statements that use the variables and to uphold the principle of narrowest scope or does this sacrifice succinctness and readability just to unnecessarily uphold an agreed 'best practice' principle? I usually declare local variables to functions/methods at the start of the function to aid readability, but I could not do this, and just create blocks throughout the function and declare the variables throughout the code - within those blocks - to narrow their scope.

    Read the article

  • How to pass results of bc to a variable

    - by shaolin
    I'm writing a script and I would like to pass the results from bc into a variable. I've declared 2 variables (var1 and var2) and have given them values. In my script I want to pass the results from bc into another variable say var3 so that I can work with var3 for other calculations. So far I have been able write the result to a file which is not what I'm looking for and also I've been able to echo the result in the terminal but I just want to pass the result to a variable at moment so that I can work with that variable. echo "scale=2;$var1/var2" | bc

    Read the article

  • Giving my function access to outside variable

    - by brett
    I have an array outside: $myArr = array(); I would like to give my function access to the array outside it so it can add values to it function someFuntion(){ $myVal = //some processing here to determine value of $myVal $myArr[] = $myVal; } How do I give the function the right scoping to the variable?

    Read the article

  • ngGrid reusable filter AngularJS

    - by wootscootinboogie
    I have a business requirement that I filter a boolean value in my ngGrid. The filter has three states: only true, only false and both. Filtering like this seems to be a common enough use case that I should refactor that functionality out of my code for re use (possibly in a directive/filter?). I'd like to know how I can go about pulling out the customFilter function in my controller and make it so that I can pass the filter a property name on which to filter, and a value for selectedFilterOption. The code currently works, but I feel like this is a good chance to get better at angular :). So how can I pull out my filtering used here and make it a reusable piece of functionality? app.controller('DocumentController',function($scope,DocumentService) { $scope.filterOptions = { filterText: '', useExternalFilter: false }; $scope.totalServerItems =0; $scope.pagingOptions ={ pageSizes: [5,10,100], pageSize: 5, currentPage: 1 } //filter! $scope.dropdownOptions = [{ name: 'Show all' },{ name: 'Show active' },{ name: 'Show trash' }]; //default choice for filtering is 'show active' $scope.selectedFilterOption = $scope.dropdownOptions[1]; //three stage bool filter $scope.customFilter = function(data){ var tempData = []; angular.forEach(data,function(item){ if($scope.selectedFilterOption.name === 'Show all'){ tempData.push(item); } else if($scope.selectedFilterOption.name ==='Show active' && !item.markedForDelete){ tempData.push(item); } else if($scope.selectedFilterOption.name ==='Show trash' && item.markedForDelete){ tempData.push(item); } }); return tempData; } //grabbing data $scope.getPagedDataAsync = function(pageSize, page, filterValue, searchText){ var data; if(searchText){ var ft = searchText.toLowerCase(); DocumentService.get('filterableData.json').success(function(largeLoad){ //filter the data when searching data = $scope.customFilter(largeLoad).filter(function(item){ return JSON.stringify(item).toLowerCase().indexOf(ft) != -1; }) $scope.setPagingData($scope.customFilter(data),page,pageSize); }) } else{ DocumentService.get('filterableData.json').success(function(largeLoad){ var testLargeLoad = $scope.customFilter(largeLoad); //filter the data on initial page load when no search text has been entered $scope.setPagingData(testLargeLoad,page,pageSize); }) } }; //paging $scope.setPagingData = function(data, page, pageSize){ var pagedData = data.slice((page -1) * pageSize, page * pageSize); //filter the data for paging $scope.myData = $scope.customFilter(pagedData); $scope.myData = pagedData; $scope.totalServerItems = data.length; if(!$scope.$$phase){ $scope.$apply(); } } //watch for filter option change, set the data property of gridOptions to the newly filtered data $scope.$watch('selectedFilterOption',function(){ var data = $scope.customFilter($scope.myData); $scope.myData = data; $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage); $scope.setPagingData($scope.myData,$scope.pagingOptions.currentPage,$scope.pagingOptions.pageSize); }) $scope.$watch('pagingOptions',function(newVal, oldVal){ if(newVal !== oldVal && newVal.currentPage !== oldVal.currentPage){ $scope.getPagedDataAsync($scope.pagingOptions.pageSize,$scope.pagingOptions.currentPage,$scope.filterOptions.filterText); } },true) $scope.message ="This is a message"; $scope.gridOptions = { data: 'myData', enablePaging: true, showFooter:true, totalServerItems: 'totalServerItems', pagingOptions: $scope.pagingOptions, filterOptions: $scope.filterOptions, showFilter: true, enableCellEdit: true, showColumnMenu: true, enableColumnReordering: true, enablePinning: true, showGroupPanel: true, groupsCollapsedByDefault: true, enableColumnResize: true } //get the data on page load $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage); }); HTML

    Read the article

  • What is required for a scope in an injection framework?

    - by johncarl
    Working with libraries like Seam, Guice and Spring I have become accustomed to dealing with variables within a scope. These libraries give you a handful of scopes and allow you to define your own. This is a very handy pattern for dealing with variable lifecycles and dependency injection. I have been trying to identify where scoping is the proper solution, or where another solution is more appropriate (context variable, singleton, etc). I have found that if the scope lifecycle is not well defined it is very difficult and often failure prone to manage injections in this way. I have searched on this topic but have found little discussion on the pattern. Is there some good articles discussing where to use scoping and what are required/suggested prerequisites for scoping? I interested in both reference discussion or your view on what is required or suggested for a proper scope implementation. Keep in mind that I am referring to scoping as a general idea, this includes things like globally scoped singletons, request or session scoped web variable, conversation scopes, and others. Edit: Some simple background on custom scopes: Google Guice custom scope Some definitions relevant to above: “scoping” - A set of requirements that define what objects get injected at what time. A simple example of this is Thread scope, based on a ThreadLocal. This scope would inject a variable based on what thread instantiated the class. Here's an example of this: “context variable” - A repository passed from one object to another holding relevant variables. Much like scoping this is a more brute force way of accessing variables based on the calling code. Example: methodOne(Context context){ methodTwo(context); } methodTwo(Context context){ ... //same context as method one, if called from method one } “globally scoped singleton” - Following the singleton pattern, there is one object per application instance. This applies to scopes because there is a basic lifecycle to this object: there is only one of these objects instantiated. Here's an example of a JSR330 Singleton scoped object: @Singleton public void SingletonExample{ ... } usage: public class One { @Inject SingeltonExample example1; } public class Two { @Inject SingeltonExample example2; } After instantiation: one.example1 == two.example2 //true;

    Read the article

  • Is it OK to use dynamic typing to reduce the amount of variables in scope?

    - by missingno
    Often, when I am initializing something I have to use a temporary variable, for example: file_str = "path/to/file" file_file = open(file) or regexp_parts = ['foo', 'bar'] regexp = new RegExp( regexp_parts.join('|') ) However, I like to reduce the scope my variables to the smallest scope possible so there is less places where they can be (mis-)used. For example, I try to use for(var i ...) in C++ so the loop variable is confined to the loop body. In these initialization cases, if I am using a dynamic language, I am then often tempted to reuse the same variable in order to prevent the initial (and now useless) value from being used latter in the function. file = "path/to/file" file = open(file) regexp = ['...', '...'] regexp = new RegExp( regexp.join('|') ) The idea is that by reducing the number of variables in scope I reduce the chances to misuse them. However this sometimes makes the variable names look a little weird, as in the first example, where "file" refers to a "filename". I think perhaps this would be a non issue if I could use non-nested scopes begin scope1 filename = ... begin scope2 file = open(filename) end scope1 //use file here //can't use filename on accident end scope2 but I can't think of any programming language that supports this. What rules of thumb should I use in this situation? When is it best to reuse the variable? When is it best to create an extra variable? What other ways do we solve this scope problem?

    Read the article

  • ipv6 : why ndp resolves to global scope address?

    - by Julien
    I'm facing a strange ipv6 behavior and I don't know how to solve it because I'm not familiar with ipv6. Maybe this behavior is normal. I hope that you will help me. ( I'm running under debian 6.0.9 with a custom kernel 3.2.58 ) machine A is "2a00:7d30:edf6:100::1" wants to ping machine B, which is "2a00:7d30:edf6:100::10". Both are on the same segment. machine A asks for the address of machine B and I don't understand why machine B gives its global scope address instead of the local scope one ? 10:59:02.082785 IP6 2a00:7d30:edf6:100::1 ff02::1:ff00:10: ICMP6, neighbor solicitation, who has 2a00:7d30:edf6:100::10, length 32 10:59:02.082821 IP6 2a00:7d30:edf6:100::10 2a00:7d30:edf6:100::1: ICMP6, neighbor advertisement, tgt is 2a00:7d30:edf6:100::10, length 32 after that machine A pings the global scope address of machine B and it works fine : 10:59:02.082927 IP6 2a00:7d30:edf6:100::1 2a00:7d30:edf6:100::10: ICMP6, echo request, seq 1, length 64 10:59:02.082960 IP6 2a00:7d30:edf6:100::10 2a00:7d30:edf6:100::1: ICMP6, echo reply, seq 1, length 64 Thank you for you help best regards Julien

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >