In ES6, how the methods of a JavaScript object are handled when they are created using a constructor - javascript-objects

Please see the below code
class Person{
constructor(){
this.name = 'John';
}
displayName(){
console.log(this.name);
}
}
let john = new Person();
console.log(john.displayName());
console.log(john.__proto__.displayName()); //It doesn't print the name
console.log(john);
I understand(from the above example) the methods in ES6 are placed as members in constructor's prototype(i.e. Person). i.e. : Person.prototype.displayName() which is assigned to john.proto.displayName()
My question here is, I am able to print name to the console by typing console.log(john.displayName()) but not by using console.log(john.proto.displayName()).
Also I am able to print the method definition by typing console.log(john.proto.displayName) but I am unable to call it.(using proto).

When you are accessing john.displayName(), you are accessing name property which have value 'John'. This is because the constructor function of the Person have run for it and the property name was assigned value 'John'.
But when you are running john.__proto__.displayName(), you are accessing the property of prototype of john object, ie. Person. Here the constructor function is not run. Therefore the value of name property is undefined.

When accessing john.__proto__.displayName you essentially calling it "statically" which means the constructor is not ran, and any properties assign to "this" on it, are not there so this.name at that point is undefined.

Related

Instance an object in an array which is an attribute of antoher object

What is the correct way of declaring an instance of an object which is part of an array that is an attribute of another object? I have a class called ingrediente which is quite simple. It looks like this:
public class ingrediente{
public int cantidad;
public String nombre;
public int fechaDeCaducidad;}
I have another class called receta which has an array of ingrediente objects:
public class receta{
ingrediente [] ingredientes;
String preparacion;
String nombreReceta;}
I want to give values to the attributes of an ingrediente object which is part of the array ingredientes in an instance of the receta class. I'm not even sure if I have to declare the ingrediente object before giving values to it, but the code doesn't work (although it doesn't show syntax errors) wether I do it or not. The code looks like this:
recetas [CONTADORRECETAS].ingredientes [CONTADORINGREDIENTES2] = new ingrediente ();
recetas [CONTADORRECETAS].ingredientes [CONTADORINGREDIENTES2].nombre = TEMP2;
Can anybody tell me what I'm doing wrong? The code is inside a try and it throws java.lang.NullPointerException on those lines (on the first one if I include it and on second one if I don't). The value of the attribute doesn't get asigned. Variable TEMP2 is previously declarated and is of the correct type.

What does static refer to being "stuck" to?

I'm trying to give myself a mapped idea of the word static (using my current noun definition of static, not having a good understanding of the adjective definition), but it would seem that non-static variables and methods actually are "stuck" (or better said referencing/referring) to objects/instances. So what is the terminology static actually describing about the declared methods/variables?
The words "static" and "dynamic" are frequently used as opposites in programming terminology.
Something that is dynamic is something that changes; in the context of a class, it is something that takes on different values or behaviors with each instance (object).
Something that is static does not change; it is in stasis. So a static variable of a class does not take on different values with each instance.
Static electricity doesn't move; it is stuck in one place, on your socks. Dynamic electricity, in motion in a wire, can do much more powerful things.
I think this question here provides a very detailed answer: What is "static"?
The concept of static has to do with whether something is part of a class or an object (instance).
In the case of the main method which is declared as static, it says that the main method is an class method -- a method that is part of a class, not part of an object. This means that another class could call a class method of another class, by referring to the ClassName.method. For example, invoking the run method of MyClass would be accomplished by:
MyClass.main(new String[]{"parameter1", "parameter2"});
On the other hand, a method or field without the static modifier means that it is part of an object (or also called "instance") and not a part of a class. It is referred to by the name of the specific object to which the method or field belongs to, rather than the class name:
MyClass c1 = new MyClass();
c1.getInfo() // "getInfo" is an instance method of the object "c1"
As each instance could have different values, the values of a method or field with the same name in different objects don't necessarily have to be the same:
MyClass c1 = getAnotherInstance();
MyClass c2 = getAnotherInstance();
c1.value // The field "value" for "c1" contains 10.
c2.value // The field "value" for "c2" contains 12.
// Because "c1" and "c2" are different instances, and
// "value" is an instance field, they can contain different
// values.
Combining the two concepts of instance and class variables. Let's say we declare a new class which contains both instance and class variables and methods:
class AnotherClass {
private int instanceVariable;
private static int classVariable = 42;
public int getInstanceVariable() {
return instanceVariable;
}
public static int getClassVariable() {
return classVariable;
}
public AnotherClass(int i) {
instanceVariable = i;
}
}
The above class has an instance variable instanceVariable, and a class variable classVariable which is declared with a static modifier. Similarly, there is a instance and class method to retrieve the values.
The constructor for the instance takes a value to assign to the instance variable as the argument. The class variable is initialized to be 42 and never changed.
Let's actually use the above class and see what happens:
AnotherClass ac1 = new AnotherClass(10);
ac1.getInstanceVariable(); // Returns "10"
AnotherClass.getClassVariable(); // Returns "42"
Notice the different ways the class and instance methods are called. The way they refer to the class by the name AnotherClass, or the instance by the name ac1. Let's go further and see the behavioral differences of the methods:
AnotherClass ac1 = new AnotherClass(10);
AnotherClass ac2 = new AnotherClass(20);
ac1.getInstanceVariable(); // Returns "10"
AnotherClass.getClassVariable(); // Returns "42"
ac2.getInstanceVariable(); // Returns "20"
AnotherClass.getClassVariable(); // Returns "42"
As can be seen, an instance variable is one that is held by an object (or "instance"), therefore unique to that particular instance, which in this example is the objects referred to by ac1 and ac2.
A class variable on the other hand is only unique to that entire class. To get this point across even better, let's add a new method to the AnotherClass:
public int getClassVariableFromInstance() {
return classVariable;
}
Then, run the following:
AnotherClass ac1 = new AnotherClass(10);
AnotherClass ac2 = new AnotherClass(20);
ac1.getInstanceVariable(); // Returns "10"
ac1.getClassVariableFromInstance(); // Returns "42"
ac2.getInstanceVariable(); // Returns "20"
ac2.getClassVariableFromInstance(); // Returns "42"
Although getClassVariableFromInstance is an instance method, as can be seen by being invoked by referring to the instances ac1 and ac2, they both return the same value, 42. This is because in both instance methods, they refer to the class method classVariable which is unique to the class, not to the instance -- there is only a single copy of classVariable for the class AnotherClass.
I hope that some what clarifies what the static modifier is used for.
The Java Tutorials from Sun has a section called Understanding Instance and Class Members, which also goes into the two types of variables and methods.

db.expando + App Engine + Change an integer property value to float value

I've following model set up initially
class Obj (db.Model):
name = db.StringProperty(required=True)
rating = db.IntegerProperty(default=0, required=False)
There are entities already created with above, such as:
name="test1", rating="3"
So, I need to change the rating type to float. I was trying to achieve this with db.Expando
class Obj (db.Expando):
name = db.StringProperty(required=True)
rating = db.FloatProperty(default=0, required=False)
Before I'm able to retrieve the instance of the Obj model to update it to float value, I've already got the following error:
Property rating must be a float
At first, I got this error, because I wasn't using db.Expando. However, after using db.Expando, I assumed this error shouldn't come into place ? Since it can dynamically change value, type etc as I read the articles.
Being new to db.Expando, I need help. Does anyone have clue to what happened ?
EDIT
for o in Obj.all():
a = []
if o.rating:
o.rating = float(str(restaurant.rating))
else:
o.rating = float(0)
a.append(restaurant)
db.put(a)
After having above code, the same error pops up
Property rating must be a float
SOLUTION
Temporarily removed the rating from model definition and updated the values to float first and then add the new rating definition with db.FloatProperty
A db.Expando model allows you to add properties that aren't defined in the class itself; however, any properties that are explicitly defined in the class do need to be the correct type.
Simply removing rating from the model definition may work for you.

Convert String into an object instance name

I'm trying to turn an string into an instance name.
stage.focus = ["box_"+[i+1]];
this gives me back = box_2;
but I need it to be an object not a string.
In as2 I could use eval. How do I do it in as3?
The correct syntax is:
this["box_"+(i+1)]
For example if you would like to call the function "start" in your main class, you'd do it this way:
this["start"]();
Same thing goes for variables. Since all classes are a subclass of Object you can retrieve their variables like you would with an ordinary object. A class like this:
package{
import flash.display.Sprite;
public class Main extends Sprite{
public var button:Sprite;
public function Main(){
trace(this["button"]);
}
}
}
Would output:
[object Sprite]
If you want to access a member of the current class, the answers already given will work. But if the instance you are looking isn't part of the class, you are out of luck.
For example:
private function foo():void {
var box_2:Sprite;
trace(this["box_"+(i+1)]);
}
Won't work, because box_2 isn't a part of the class. In that case, it is highly recommended to use an array.
If you want to access a DisplayObject (for example, a Sprite or a MovieClip) you also can use getChildByName. But in that case, box_2 will be the name of the object, instead of the name of the variable. You set the name like
var box:Sprite;
box.name = "box_2";
But again, I recommend an array.

Can someone explain the magic going on in Prism's resolve<> method?

I've got a CustomersModule.cs with the following Initialize() method:
public void Initialize()
{
container.RegisterType<ICustomersRepository, CustomersRepository>(new ContainerControlledLifetimeManager());
CustomersPresenter customersPresenter = this.container.Resolve<CustomersPresenter>();
}
The class I resolve from the container looks like this:
class CustomersPresenter
{
private CustomersView view;
private ICustomersRepository customersRespository;
public CustomersPresenter(CustomersView view,
ICustomersRepository customersRepository,
TestWhatever testWhatever)
{
this.view = view;
this.customersRespository = customersRepository;
}
}
The TestWhatever class is just a dummy class I created:
public class TestWhatever
{
public string Title { get; set; }
public TestWhatever()
{
Title = "this is the title";
}
}
Yet the container happily resolves CustomersPresenter even though I never registered it, and also the container somehow finds TestWhatever, instantiates it, and injects it into CustomersPresenter.
I was quite surprised to realize this since I couldn't find anywhere in the Prism documentation which explicitly stated that the container was so automatic.
So this is great, but it what else is the container doing that I don't know about i.e. what else can it do that I don't know about? For example, can I inject classes from other modules and if the modules happen to be loaded the container will inject them, and if not, it will inject a null?
There is nothing magical going on. You are specifying concrete types, so naturally they are resolvable, because if we have the Type object, we can call a constructor on it.
class Fred { };
Fred f1 = new Fred();
Type t = typeof(Fred);
Fred f2 = (Fred)t.GetConstructor(Type.EmptyTypes).Invoke(null);
The last line above is effectively what happens, the type t having been found by using typeof on the type parameter you give to Resolve.
If the type cannot be constructed by new (because it's in some unknown separate codebase) then you wouldn't be able to give it as a type parameter to Resolve.
In the second case, it is constructor injection, but it's still a known concrete constructable type. Via reflection, the Unity framework can get an array of all the Types of the parameters to the constructor. The type TestWhatever is constructable, so there is no ambiguity or difficulty over what to construct.
As to your concern about separate modules (assemblies), if you move TestWhatever to another assembly, that will not change the lines of code you've written; it will just mean that you have to add a reference to the other assembly to get this one to build. And then TestWhatever is still an unambiguously refeferenced constructable type, so it can be constructed by Unity.
In other words, if you can refer to the type in code, you can get a Type object, and so at runtime it will be directly constructable.
Response to comment:
If you delete the class TestWhatever, you will get a compile-time error, because you refer to that type in your code. So it won't be possible to get a runtime by doing that.
The decoupling is still in effect in this arrangement, because you could register a specific instance of TestWhatever, so every call to Resolve<TestWhatever>() will get the same instance, rather than constructing a new one.
The reason this works is because Unity is designed for it. When you Resolve with a concrete type, Unity looks to see if it can resolve from the container. If it cannot, then it just goes and instantiates the type resolving it's dependencies. It's really quite simple.

Resources