Search Results

Search found 4652 results on 187 pages for 'explicit constructor'.

Page 11/187 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • NTFS Permissions - Access Denied even though Explicit Allow and no Deny

    - by chris613
    I'm hoping someone can help me with this NTFS permissions problem. The short version is that I can't write a new file in F:\SomeDir even though I seem to be granted full permissions via both the "Domain Admins" group and a second unprivileged group. The "Effective Permissions" tab in the explorer permissions UI shows that I have full control, and there are no "Deny"s anywhere in the ACL or anything else that looks unusual. I am logged into the machine over RDP and accessing the disk directly, not through a share. F:\SomeDir>set U USERDNSDOMAIN=THEOFFICE.LOCAL USERDOMAIN=THEOFFICE USERNAME=thisisme USERPROFILE=C:\Users\thisisme F:\SomeDir>icacls . . BUILTIN\Administrators:(I)(F) CREATOR OWNER:(I)(OI)(CI)(IO)(F) THEOFFICE\Domain Admins:(I)(OI)(CI)(F) NT AUTHORITY\SYSTEM:(I)(OI)(CI)(F) BUILTIN\Administrators:(I)(OI)(CI)(IO)(F) BUILTIN\Users:(I)(OI)(CI)(RX) Successfully processed 1 files; Failed processing 0 files F:\SomeDir>net group /domain "Domain Admins" The request will be processed at a domain controller for domain THEOFFICE.local. Group name Domain Admins Comment Designated administrators of the domain Members ------------------------------------------------------------------------------- Administrator thatguy thisisme The command completed successfully. F:\SomeDir>echo "whyUNoCreateFile?" > whyUNoCreateFile.txt Access is denied. I searched for answers and came across similar problems that lead to UAC (ex. Why does removing the EVERYONE group prevent domain admins from accessing a drive? ). I can't turn off UAC at the moment, so I try a "regular" group that I'm also part of. This group has no special rights assignments and is not part of any administrative groups. Still no dice: [***** This one command executed in an elevated shell *****] F:\SomeDir>icacls . /grant THEOFFICE\iteveryone:(OI)(CI)F processed file: . Successfully processed 1 files; Failed processing 0 files F:\SomeDir>net group /domain "iteveryone" The request will be processed at a domain controller for domain THEOFFICE.local. Group name ITeveryone Comment Members ------------------------------------------------------------------------------- Administrator thatguy thisisme otherguy someitguy The command completed successfully. F:\ScanningVMsForIBM>echo y > u Access is denied. As you can see, using a "regular" group didn't help. I have logged out and back in to the server to ensure my login token is up to date, and at any rate I belonged to these groups before the server was created. If I grant explicit permission to myself, it does allow me to write files: [***** This one command executed in an elevated shell *****] F:\SomeDir>icacls . /grant THEOFFICE\thisisme:(OI)(CI)F processed file: . Successfully processed 1 files; Failed processing 0 files F:\SomeDir>echo y > u F:\SomeDir>type u y My requirement is for the "Domain Admins" group to have Full Control, or if that's not possible without disabling UAC, then a second group will do, but I can't get either to work. I'm really stumped. Can someone please point out what I could be overlooking?

    Read the article

  • Is this a good or bad way to use constructor chaining? (... to allow for testing).

    - by panamack
    My motivation for chaining my class constructors here is so that I have a default constructor for mainstream use by my application and a second that allows me to inject a mock and a stub. It just seems a bit ugly 'new'-ing things in the ":this(...)" call and counter-intuitive calling a parametrized constructor from a default constructor , I wondered what other people would do here? (FYI - SystemWrapper) using SystemWrapper; public class MyDirectoryWorker{ // SystemWrapper interface allows for stub of sealed .Net class. private IDirectoryInfoWrap dirInf; private FileSystemWatcher watcher; public MyDirectoryWorker() : this( new DirectoryInfoWrap(new DirectoryInfo(MyDirPath)), new FileSystemWatcher()) { } public MyDirectoryWorker(IDirectoryInfoWrap dirInf, FileSystemWatcher watcher) { this.dirInf = dirInf; if(!dirInf.Exists){ dirInf.Create(); } this.watcher = watcher; watcher.Path = dirInf.FullName; watcher.NotifyFilter = NotifyFilters.FileName; watcher.Created += new FileSystemEventHandler(watcher_Created); watcher.Deleted += new FileSystemEventHandler(watcher_Deleted); watcher.Renamed += new RenamedEventHandler(watcher_Renamed); watcher.EnableRaisingEvents = true; } public static string MyDirPath{get{return Settings.Default.MyDefaultDirPath;}} // etc... }

    Read the article

  • html.checkbox - explicit value to hidden field value

    - by Tassadaque
    Hi I am creating list of checkboxes in partial view by follwoing http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ code and Rendered HTML for checkboxes is as follows <%=Html.CheckBox("EmployeeID", new { value = user.EmployeeID, @class = "ccboxes", title = user.Designation + "(" + user.EmployeeName + ")" })%> <INPUT id=MemoUsers_a29f82e4-ebbc-47b0-8cdd-7d54f94143be__EmployeeID class=boxes title=Programmer(Zia) value=6 type=checkbox name=MemoUsers[a29f82e4-ebbc-47b0-8cdd-7d54f94143be].EmployeeID jQuery1276681299292="27"> <INPUT value=false type=hidden name=MemoUsers[a29f82e4-ebbc-47b0-8cdd-7d54f94143be].EmployeeID> In rendered html it can be seen that value attribute of hidden field is false. i want to assign explicit value(same as checkbox value) to this value. Is this possible using html.checkbox or html.checkboxfor. one way is recommended in http://stackoverflow.com/questions/626901/asp-net-mvc-rc2-checkboxes-with-explicit-values. Is there any other better way i want to do this as ModelState.IsValid is returning false because of hidden field value attribute Regards

    Read the article

  • Constructor or Explicit cast

    - by Felan
    In working with Linq to Sql I create a seperate class to ferry data to a web page. To simplify creating these ferry objects I either use a specialized constructor or an explicit conversion operator. I have two questions. First which approach is better from a readibility perspective? Second while the clr code that is generated appeared to be the same to me, are there situations where one would be treated different than the other by the compiler (in lambda's or such). Example code (DatabaseFoo uses specialized constructor and BusinessFoo uses explicit operator): public class DatabaseFoo { private static int idCounter; // just to help with generating data public int Id { get; set; } public string Name { get; set; } public DatabaseFoo() { Id = idCounter++; Name = string.Format("Test{0}", Id); } public DatabaseFoo(BusinessFoo foo) { this.Id = foo.Id; this.Name = foo.Name; } } public class BusinessFoo { public int Id { get; set; } public string Name { get; set; } public static explicit operator BusinessFoo(DatabaseFoo foo) { return FromDatabaseFoo(foo); } public static BusinessFoo FromDatabaseFoo(DatabaseFoo foo) { return new BusinessFoo {Id = foo.Id, Name = foo.Name}; } } public class Program { static void Main(string[] args) { Console.WriteLine("Creating the initial list of DatabaseFoo"); IEnumerable<DatabaseFoo> dafoos = new List<DatabaseFoo>() { new DatabaseFoo(), new DatabaseFoo(), new DatabaseFoo(), new DatabaseFoo(), new DatabaseFoo(), new DatabaseFoo()}; foreach(DatabaseFoo dafoo in dafoos) Console.WriteLine(string.Format("{0}\t{1}", dafoo.Id, dafoo.Name)); Console.WriteLine("Casting the list of DatabaseFoo to a list of BusinessFoo"); IEnumerable<BusinessFoo> bufoos = from x in dafoos select (BusinessFoo) x; foreach (BusinessFoo bufoo in bufoos) Console.WriteLine(string.Format("{0}\t{1}", bufoo.Id, bufoo.Name)); Console.WriteLine("Creating a new list of DatabaseFoo by calling the constructor taking BusinessFoo"); IEnumerable<DatabaseFoo> fufoos = from x in bufoos select new DatabaseFoo(x); foreach(DatabaseFoo fufoo in fufoos) Console.WriteLine(string.Format("{0}\t{1}", fufoo.Id, fufoo.Name)); } }

    Read the article

  • Passing IDisposable objects through constructor chains

    - by Matt Enright
    I've got a small hierarchy of objects that in general gets constructed from data in a Stream, but for some particular subclasses, can be synthesized from a simpler argument list. In chaining the constructors from the subclasses, I'm running into an issue with ensuring the disposal of the synthesized stream that the base class constructor needs. Its not escaped me that the use of IDisposable objects this way is possibly just dirty pool (plz advise?) for reasons I've not considered, but, this issue aside, it seems fairly straightforward (and good encapsulation). Codes: abstract class Node { protected Node (Stream raw) { // calculate/generate some base class properties } } class FilesystemNode : Node { public FilesystemNode (FileStream fs) : base (fs) { // all good here; disposing of fs not our responsibility } } class CompositeNode : Node { public CompositeNode (IEnumerable some_stuff) : base (GenerateRaw (some_stuff)) { // rogue stream from GenerateRaw now loose in the wild! } static Stream GenerateRaw (IEnumerable some_stuff) { var content = new MemoryStream (); // molest elements of some_stuff into proper format, write to stream content.Seek (0, SeekOrigin.Begin); return content; } } I realize that not disposing of a MemoryStream is not exactly a world-stopping case of bad CLR citizenship, but it still gives me the heebie-jeebies (not to mention that I may not always be using a MemoryStream for other subtypes). It's not in scope, so I can't explicitly Dispose () it later in the constructor, and adding a using statement in GenerateRaw () is self-defeating since I need the stream returned. Is there a better way to do this? Preemptive strikes: yes, the properties calculated in the Node constructor should be part of the base class, and should not be calculated by (or accessible in) the subclasses I won't require that a stream be passed into CompositeNode (its format should be irrelevant to the caller) The previous iteration had the value calculation in the base class as a separate protected method, which I then just called at the end of each subtype constructor, moved the body of GenerateRaw () into a using statement in the body of the CompositeNode constructor. But the repetition of requiring that call for each constructor and not being able to guarantee that it be run for every subtype ever (a Node is not a Node, semantically, without these properties initialized) gave me heebie-jeebies far worse than the (potential) resource leak here does.

    Read the article

  • How does initializing inherited members inside base class constructor reduce the calls to…?

    - by flockofcode
    I’ve read that instead of initializing inherited members ( _c1 in our example ) inside derived constructor: class A { public int _c; } class B:A { public B(int c) { _c = c; } } we should initialize them inside base class constructor, since that way we reduce the calls to inherited members ( _c ): class A { public A(int c) { _c = c; } public int _c; } class B:A { public B(int c) : base(c) { } } If _c field is initialized inside base constructor, the order of initialization is the following: 1) First the field initializers of derived class B are called 2) Then field initializers of base class A are called (at this point _c is set to value 0) 3) B’s constructor is called, which in turn calls A’s custom constructor 4) _c field gets set to value of a parameter c ( inside A’s custom constructor ) 5) Once A’s custom constructor returns, B’s constructor executes its code. If _c field is initialized inside B's constructor, the order of initialization is the following: 1) First the field initializers of a derived class B are called 2) Then field initializers of a base class A are called(at this point _c is set to value 0) 3) B’s constructor is called, which in turn calls A’s default constructor 4) Once A’s custom constructor returns, B’s constructor sets _c field to a value of parameter c As far as I can tell, in both cases was _c called two times, so how exactly did we reduce calls to inherited member _c? thanx

    Read the article

  • Spring constructor injection of SLF4J logger - how to get injection target class?

    - by disown
    I'm trying to use Spring to inject a SLF4J logger into a class like so: @Component public class Example { private final Logger logger; @Autowired public Example(final Logger logger) { this.logger = logger; } } I've found the FactoryBean class, which I've implemented. But the problem is that I cannot get any information about the injection target: public class LoggingFactoryBean implements FactoryBean<Logger> { @Override public Class<?> getObjectType() { return Logger.class; } @Override public boolean isSingleton() { return false; } @Override public Logger getObject() throws Exception { return LoggerFactory.getLogger(/* how do I get a hold of the target class (Example.class) here? */); } } Is FactoryBean even the right way to go? When using picocontainers factory injection, you get the Type of the target passed in. In guice it is a bit trickier. But how do you accomplish this in Spring?

    Read the article

  • Why would the assignment operator ever do something different than its matching constructor?

    - by Neil G
    I was reading some boost code, and came across this: inline sparse_vector &assign_temporary(sparse_vector &v) { swap(v); return *this; } template<class AE> inline sparse_vector &operator=(const sparse_vector<AE> &ae) { self_type temporary(ae); return assign_temporary(temporary); } It seems to be mapping all of the constructors to assignment operators. Great. But why did C++ ever opt to make them do different things? All I can think of is scoped_ptr?

    Read the article

  • Why isn't the "this." command needed in this constructor? (java)

    - by David
    I'm reading a book about java. It just got to explaining how you create a class called "deck" which contains an array of cards as its instance variable(s). Here is the code snippit: class Deck { Card[] cards; public Deck (int n) { cards = new Card[n]; } } why isn't the this. command used? for example why isn't the code this: class Deck { Card[[] cards; public Deck (int n) { this.cards = new Card[n]; } }

    Read the article

  • How can I create a generic constructor? (ie. BaseClass.FromXml(<param>)

    - by SofaKng
    I'm not sure how to describe this but I'm trying to create a base class that contains a shared (factory) function called FromXml. I want this function to instantiate an object of the proper type and then fill it via an XmlDocument. For example, let's say I have something like this: Public Class XmlObject Public Shared Function FromXml(ByVal source as XmlDocument) As XmlObject // <need code to create SPECIFIC TYPE of object and return it End Function End Class Public Class CustomObject Inherits XmlObject End Class I'd like to be able to do something like this: Dim myObject As CustomObject = CustomObject.FromXml(source) Is this possible?

    Read the article

  • How to use a object whose copy constructor and copy assignment is private?

    - by coanor
    In reading TCPL, I got a problem, as the title refered, and then 'private' class is: class Unique_handle { private: Unique_handle& operator=(const Unique_handle &rhs); Unique_handle(const Unique_handle &rhs); public: //... }; the using code is: struct Y { //... Unique_handle obj; }; and I want to execute such operations: int main() { Y y1; Y y2 = y1; } although, these code are come from TCPL, but I still can not got the solution... Can anybody help me, appreciate.

    Read the article

  • Definition of variables/fields type within a constructor, how is it done?

    - by elementz
    I just had a look at Suns Java tutorial, and found something that totally confused me: Given the following example: public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } Why is it, that the types of the variables (fields?) gear, cadence and speed do not need to be defined? I would have written it as follows: public Bicycle(int startCadence, int startSpeed, int startGear) { int gear = startGear; int cadence = startCadence; int speed = startSpeed; } What would be the actual differnce?

    Read the article

  • When exactly is constructor of static local object called?

    - by Honza Bambas
    Say we have a code like this: Some class { Some() { // the ctor code } }; Some& globalFunction() { static Some gSome; return gSome; } When exactly 'the ctor code' is executed? As for normal static variables before main() or at the moment we first call to 'globalFunction()'? How is it on different platforms and different compilers (cl, gcc, ...) ? Thanks -hb-

    Read the article

  • Using an interface as a constructor parameter in Java?

    - by aperson
    How would I be able to accomplish the following: public class testClass implements Interface { public testClass(Interface[] args) { } } So that I could declare Interface testObject = new testClass(new class1(4), new class2(5)); Where class1 and class2 are also classes that implement Interface. Also, once I accomplish this, how would I be able to refer to each individual parameter taken in to be used in testClass? Thanks :)

    Read the article

  • Copy Constructors and calling functions

    - by helixed
    Hello, I'm trying to call an accessor function in a copy constructor but it's not working. Here's an example of my problem: A.h class A { public: //Constructor A(int d); //Copy Constructor A(const A &rhs); //accessor for data int getData(); //mutator for data void setData(int d); private: int data; }; A.cpp #include "A.h" //Constructor A::A(int d) { this->setData(d); } //Copy Constructor A::A(const A &rhs) { this->setData(rhs.getData()); } //accessor for data int A::getData() { return data; } //mutator for data void A::setData(int d) { data = d; } When I try to compile this, I get the following error: error: passing 'const A' as 'this' argument of 'int A::getData()' discards qualifiers If I change rhs.getData() to rhs.data, then the constructor works fine. Am I not allowed to call functions in a copy constructor? Could somebody please tell me what I'm doing wrong? Thanks, helixed

    Read the article

  • Explicit casting doesn't work in default model binding

    - by Felix
    I am using ASP.NET MVC2 and Entity Framework. I am going to simplify the situation a little; hopefully it will make it clearer, not more confusing! I have a controller action to create address, and the country is a lookup table (in other words, there is a one-to-many relationship between Country and Address classes). Let's say for clarity that the field in the Address class is called Address.Land. And, for the purposes of the dropdown list, I am getting Country.CountryID and Country.Name. I am aware of Model vs. Input validation. So, if I call the dropdown field formLand - I can make it work. But if I call the field Land (that is, matching the variable in Address class) - I am getting the following error: "The parameter conversion from type 'System.String' to type 'App.Country' failed because no type converter can convert between these types." OK, this makes sense. A string (CountryID) comes from the form and the binder doesn't know how to convert it to Country type. So, I wrote the converter: namespace App { public partial class Country { public static explicit operator Country(string countryID) { AppEntities context = new AppEntities(); Country country = (Country) context.GetObjectByKey( new EntityKey("AppEntities.Countries", "CountryID", countryID)); return country; } } } FWIW, I tried both explicit and implicit. I tested it from the controller - Country c = (Country)"fr" - and it works fine. However, it never got invoked when the View is posted. I am getting the same "no type converter" error in the model. Any ideas how to hint to the model binder that there is a type converter? Thanks

    Read the article

  • Why doesn't is operator take in consideration if the explicit operator is overriden when checking ty

    - by Galilyou
    Hey Guys, Consider this code sample: public class Human { public string Value { get; set;} } public class Car { public static explicit operator Human (Car c) { Human h = new Human(); h.Value = "Value from Car"; return h; } } public class Program { public static void Mani() { Car c = new Car(); Human h = (Human)c; Console.WriteLine("h.Value = {0}", h.Value); Console.WriteLine(c is Human); } } Up I provide a possibility of an explicit cast from Car to Human, though Car and Human hierarchically are not related! The above code simply means that "Car is convertible to human" However, if you run the snippet you will find the expression c is Human evaluates to false! I used to believe that the is operator is kinda expensive cause it attempts to do an actual cast that might result in an InvalidCastException. If the operator is trying to cast, then the cast should succeed as there's an operator logic that should perform the cast! What does "is" test? Does test a hierarchical "is-a" relationship? Does test whether a variable type is convertible to a type?

    Read the article

  • JavaScript Class Patterns

    - by Liam McLennan
    To write object-oriented programs we need objects, and likely lots of them. JavaScript makes it easy to create objects: var liam = { name: "Liam", age: Number.MAX_VALUE }; But JavaScript does not provide an easy way to create similar objects. Most object-oriented languages include the idea of a class, which is a template for creating objects of the same type. From one class many similar objects can be instantiated. Many patterns have been proposed to address the absence of a class concept in JavaScript. This post will compare and contrast the most significant of them. Simple Constructor Functions Classes may be missing but JavaScript does support special constructor functions. By prefixing a call to a constructor function with the ‘new’ keyword we can tell the JavaScript runtime that we want the function to behave like a constructor and instantiate a new object containing the members defined by that function. Within a constructor function the ‘this’ keyword references the new object being created -  so a basic constructor function might be: function Person(name, age) { this.name = name; this.age = age; this.toString = function() { return this.name + " is " + age + " years old."; }; } var john = new Person("John Galt", 50); console.log(john.toString()); Note that by convention the name of a constructor function is always written in Pascal Case (the first letter of each word is capital). This is to distinguish between constructor functions and other functions. It is important that constructor functions be called with the ‘new’ keyword and that not constructor functions are not. There are two problems with the pattern constructor function pattern shown above: It makes inheritance difficult The toString() function is redefined for each new object created by the Person constructor. This is sub-optimal because the function should be shared between all of the instances of the Person type. Constructor Functions with a Prototype JavaScript functions have a special property called prototype. When an object is created by calling a JavaScript constructor all of the properties of the constructor’s prototype become available to the new object. In this way many Person objects can be created that can access the same prototype. An improved version of the above example can be written: function Person(name, age) { this.name = name; this.age = age; } Person.prototype = { toString: function() { return this.name + " is " + this.age + " years old."; } }; var john = new Person("John Galt", 50); console.log(john.toString()); In this version a single instance of the toString() function will now be shared between all Person objects. Private Members The short version is: there aren’t any. If a variable is defined, with the var keyword, within the constructor function then its scope is that function. Other functions defined within the constructor function will be able to access the private variable, but anything defined outside the constructor (such as functions on the prototype property) won’t have access to the private variable. Any variables defined on the constructor are automatically public. Some people solve this problem by prefixing properties with an underscore and then not calling those properties by convention. function Person(name, age) { this.name = name; this.age = age; } Person.prototype = { _getName: function() { return this.name; }, toString: function() { return this._getName() + " is " + this.age + " years old."; } }; var john = new Person("John Galt", 50); console.log(john.toString()); Note that the _getName() function is only private by convention – it is in fact a public function. Functional Object Construction Because of the weirdness involved in using constructor functions some JavaScript developers prefer to eschew them completely. They theorize that it is better to work with JavaScript’s functional nature than to try and force it to behave like a traditional class-oriented language. When using the functional approach objects are created by returning them from a factory function. An excellent side effect of this pattern is that variables defined with the factory function are accessible to the new object (due to closure) but are inaccessible from anywhere else. The Person example implemented using the functional object construction pattern is: var personFactory = function(name, age) { var privateVar = 7; return { toString: function() { return name + " is " + age * privateVar / privateVar + " years old."; } }; }; var john2 = personFactory("John Lennon", 40); console.log(john2.toString()); Note that the ‘new’ keyword is not used for this pattern, and that the toString() function has access to the name, age and privateVar variables because of closure. This pattern can be extended to provide inheritance and, unlike the constructor function pattern, it supports private variables. However, when working with JavaScript code bases you will find that the constructor function is more common – probably because it is a better approximation of mainstream class oriented languages like C# and Java. Inheritance Both of the above patterns can support inheritance but for now, favour composition over inheritance. Summary When JavaScript code exceeds simple browser automation object orientation can provide a powerful paradigm for controlling complexity. Both of the patterns presented in this article work – the choice is a matter of style. Only one question still remains; who is John Galt?

    Read the article

  • JavaScript Class Patterns

    - by Liam McLennan
    To write object-oriented programs we need objects, and likely lots of them. JavaScript makes it easy to create objects: var liam = { name: "Liam", age: Number.MAX_VALUE }; But JavaScript does not provide an easy way to create similar objects. Most object-oriented languages include the idea of a class, which is a template for creating objects of the same type. From one class many similar objects can be instantiated. Many patterns have been proposed to address the absence of a class concept in JavaScript. This post will compare and contrast the most significant of them. Simple Constructor Functions Classes may be missing but JavaScript does support special constructor functions. By prefixing a call to a constructor function with the ‘new’ keyword we can tell the JavaScript runtime that we want the function to behave like a constructor and instantiate a new object containing the members defined by that function. Within a constructor function the ‘this’ keyword references the new object being created -  so a basic constructor function might be: function Person(name, age) { this.name = name; this.age = age; this.toString = function() { return this.name + " is " + age + " years old."; }; } var john = new Person("John Galt", 50); console.log(john.toString()); Note that by convention the name of a constructor function is always written in Pascal Case (the first letter of each word is capital). This is to distinguish between constructor functions and other functions. It is important that constructor functions be called with the ‘new’ keyword and that not constructor functions are not. There are two problems with the pattern constructor function pattern shown above: It makes inheritance difficult The toString() function is redefined for each new object created by the Person constructor. This is sub-optimal because the function should be shared between all of the instances of the Person type. Constructor Functions with a Prototype JavaScript functions have a special property called prototype. When an object is created by calling a JavaScript constructor all of the properties of the constructor’s prototype become available to the new object. In this way many Person objects can be created that can access the same prototype. An improved version of the above example can be written: function Person(name, age) { this.name = name; this.age = age; } Person.prototype = { toString: function() { return this.name + " is " + this.age + " years old."; } }; var john = new Person("John Galt", 50); console.log(john.toString()); In this version a single instance of the toString() function will now be shared between all Person objects. Private Members The short version is: there aren’t any. If a variable is defined, with the var keyword, within the constructor function then its scope is that function. Other functions defined within the constructor function will be able to access the private variable, but anything defined outside the constructor (such as functions on the prototype property) won’t have access to the private variable. Any variables defined on the constructor are automatically public. Some people solve this problem by prefixing properties with an underscore and then not calling those properties by convention. function Person(name, age) { this.name = name; this.age = age; } Person.prototype = { _getName: function() { return this.name; }, toString: function() { return this._getName() + " is " + this.age + " years old."; } }; var john = new Person("John Galt", 50); console.log(john.toString()); Note that the _getName() function is only private by convention – it is in fact a public function. Functional Object Construction Because of the weirdness involved in using constructor functions some JavaScript developers prefer to eschew them completely. They theorize that it is better to work with JavaScript’s functional nature than to try and force it to behave like a traditional class-oriented language. When using the functional approach objects are created by returning them from a factory function. An excellent side effect of this pattern is that variables defined with the factory function are accessible to the new object (due to closure) but are inaccessible from anywhere else. The Person example implemented using the functional object construction pattern is: var john = new Person("John Galt", 50); console.log(john.toString()); var personFactory = function(name, age) { var privateVar = 7; return { toString: function() { return name + " is " + age * privateVar / privateVar + " years old."; } }; }; var john2 = personFactory("John Lennon", 40); console.log(john2.toString()); Note that the ‘new’ keyword is not used for this pattern, and that the toString() function has access to the name, age and privateVar variables because of closure. This pattern can be extended to provide inheritance and, unlike the constructor function pattern, it supports private variables. However, when working with JavaScript code bases you will find that the constructor function is more common – probably because it is a better approximation of mainstream class oriented languages like C# and Java. Inheritance Both of the above patterns can support inheritance but for now, favour composition over inheritance. Summary When JavaScript code exceeds simple browser automation object orientation can provide a powerful paradigm for controlling complexity. Both of the patterns presented in this article work – the choice is a matter of style. Only one question still remains; who is John Galt?

    Read the article

  • http(/* argument here */) How is this Object (Http) being used without an explicit or implicit meth

    - by Randin
    In the example for coding with Json using Databinder Dispatch Nathan uses an Object (Http) without a method, shown here: import dispatch._ import Http._ Http("http://www.fox.com/dollhouse/" >>> System.out ) How is he doing this? Thank you for all of the answers unfortunatly I was not specific enough... It looks like it is simply passing an argument to a constructor of class or companion object Http. In another example, I've seen another form: http = new Http http(/* argument here */) Is this valid Scala? I guess it must be, because the author is a Scala expert. But it makes no sense to me. Actions are usually performed by invoking methods on objects, whether explicitly as object.doSomething() or implicitly as object = something (using the apply() method underneath the syntactic sugar). All I can think of is that a constructor is being used to do something in addition to constructing an object. In other words, it is having side effects, such as in this case going off and doing something on the web.

    Read the article

  • Puppet classes out of order despite explicit arrow operator use

    - by Alexandr Kurilin
    Absolute puppet beginner here. I'm experiencing an interesting behavior with my puppet manifests and would love to know what I'm doing wrong. Let's for example say I'm configuring the instance with the following ordered classes: class { 'update_system': } -> class { 'facter': } -> class { 'user_sshkey': user => 'ubuntu', type => 'rsa', } -> class { 'tmux': user => 'ubuntu', } -> class { 'vim': user => 'ubuntu', } -> class { 'bashrc': user => 'ubuntu' } -> notify {"Configuring DB role":} -> class { 'postgresql': } when I run the manifest with the --debug switch, by looking at notify statements I can see the classes be executed in the following order: 1. update_system starts 2. a cron type inside of postgresql class (the very **last** class in that ordered list above) is executed 3. postgres::install starts 5. facter starts installing 6. postgres::configure and postgres::service start 7. the vim class is executed 8. "Configuring DB role" notification is made. All the way at the end here. etc Basically the thing is all over the place, the order doesn't seem to follow the arrow operators in any way. I'm guessing I'm missing something here that would force the classes to execute one at a time. Could it be that I'm missing some kind of anchor pattern here? Invalid containment?

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >