I'm learning javascript , so don't kill me.
I'm defining more different namespaces like this :
var name_Class = function(){
this.variable_name_1 = {}
this.method_name_1 = function() {}
}
and then..
var second_name_Class = function(){
this.variable_name_1 = {}
this.method_name_1 = function() {}
}
If i define and Initialiaze a variable in the first one and I try to call it in the second one , e.g. if a write c = new name_Class() it , e.g. redefine every array to [] so I cannot get the value I gave it before. Can you help me?
I'm not sure you understand what you're doing.
This
var name_Class = function(){
this.variable_name_1 = {}
this.method_name_1 = function() {}
}
defines a constructor function called name_Class (as an aside, constructors should have their first character capitalized by convention)
This
var c = new name_Class();
creates an object using that constructor. The new object is created and the constructor is bound to that object and called, setting the variable_name_1 and method_name_1 properties of the new object c. Each time you assign new name_Class() to a variable it will create a completely new object which has the constructor bound to it. Any changes you made to other objects created to the function will not have an effect on this new variable.
All of this is completely unrelated to your second Constructor, which you can use in the same way and is not affected at all by your first one.
Neither of these things are technically namespaces, they're classes or types. A namespace generally refers to a top level variable that other variables are defined as properties on. By default variables are defined on the global namespace, which for browsers is the window.
So to create your new object with type name_Class on a namespace namespace1 for instance, you could do
var namespace1 = {};
namespace1.c = new name_Class();
You can pass in arguments if you're looking to set values on an instance. eg
var Swatch = function(){
this.color = arguments[0] || 'green';
this.callback = arguments[1] || function() {
alert(this.color);
}
this.callback();
}
//defaults to green if no args are passed
var green = new Swatch();
//or pass in your own values
var red = new Swatch('red',function(){
alert('New swatch created with color '+this.color);
});
Related
please help solve the problem.
i make 3 objects:
level:
var Level = function() {
self = this;
this.cellsObserver = new CellsObserver();
console.log('co from level ' + this.cellsObserver);
this.fieldObj = new Field();
}
field:
var Field = function() {
self = this;
this.init();
};
Field.prototype = Object.create(Level.prototype);
Field.prototype = {
init: function() {
console.log('co from field ' + self.cellsObserver);
}
}
observer:
var CellsObserver = function(){
.............
}
in result console output follow:
co from level [object Object] co from field undefined
I do not understand why in the second case output 'undefined'. because I have appointed a parent:
Field.prototype = Object.create(Level.prototype);
tl;dr: there is no field cellsObserver neither in Field or Level.prototype object. And there is no such thing as a classical 'self' in Javascript.
The long story.
When you're trying to fetch object.property, the Javascript will look at the object trying to find property, then to the object.prototype (which is another object) and so on until it get to the null prototype in the Object.prototype reference.
So, when you're calling second time the this.cellsObserver in Level constructor function, it goes like this:
this is a just new constructed object (if it called with the new keyword), and there is cellsObserver in the property list, so it'll be fetched without any deep lookup.
Then,
Field.prototype = Object.create(Level.prototype);
This only means that Field.prototype now will refer to a new object, which properties are the same as in Level.prototype in that moment.
From your code, there are no non-standard properties in Level.prototype object (you didn't provide any).
Then,
self = this;
Here you just assigning a global variable called self a reference to the just created object or window object (it depends). If you wish to store a reference to the this object, you should var: var self = this. But you should remember that this self variable could be accessed only in the scope where is was declared or in a closure.
Then,
Field.prototype = {
init: function() {
console.log('co from field ' + self.cellsObserver);
}
}
First of all, here you just override the previos instruction (Field.prototype = Object.create(Level.prototype);). If you want to extend the Field.prototype object, you could do in the Object.create call in second argument, or just by accessing a property like that: Field.prototype.init = function(){...}.
Second. The self variable could contain anything when the init function will be executed. Just use this for the current object here.
Third. Let's try to guess what will happen when this.cellsObserver get evaluated inside this init function.
The this object is referring to the Field instance, and there is no cellsObserver property there, so we move to the Field.prototype object, which is defined above ({ init: function () {...}}), there is no cellsObserver either, so we move to the Object.prototype object, which is null. Ok, our lookup is failed, this.cellsObserver is undefined.
What would be it look like if the Field.prototype = Object.create(Level.prototype) wasn't been overridden by the following code? The this object will refer to the Field instance as early. The Field.prototype is referring to the object which is copy of the Level.prototype object, and there is no cellsObserver here either. So, we look to the Object.prototype, and that's it. There is no cellsObserver in any objects except in the instances on Level class, which isn't referenced in any way in the Field instances.
You can play with that here: http://www.objectplayground.com/ by pasting this code:
var Level = function() {
this.cellsObserver = new CellsObserver();
this.fieldObj = new Field();
}
var Field = function() {
this.init();
};
Field.prototype = Object.create(Level.prototype);
Field.prototype.init = function() {};
this.field = new Field();
You are overriding the Field.prototype. Just assign to Field.prototype.init.
I am trying to make a function that has an instance variable for each assignment e.g.
function Sample() {
Sample.myInstanceVar = true; // <--- This var should be instance-specific
}
var a = Sample;
console.log(a.myInstanceVar); // should return undefined and it does
a.apply(this);
var b = Sample;
console.log(b.myInstanceVar); // i would like to get this one to return undefined here, but it returns true;
Hopefully, you get the point :-)
UPDATE:>
I am not interested in Sample being an instance since its a function i am referencing. I want Sample to have some sort of variable or instance that is specific to the scope/context i am referencing Sample in.
function Sample() {
Sample.myInstanceVar = true; // <--- This var should be instance-specific
}
No. That modifies the global object referenced by Sample
var a = Sample;
No. That copies the reference to the aforementioned global object.
How to create an instance:
var a = new Sample();
The new is the important bit. The () are optional if you have no arguments, but including them is good style.
How to define a property on an instance:
Use the this keyword. When used inside a function that is called with new it refers to the instance being created.
function Sample() {
this.myInstanceVar = true;
}
Of course, this will run for every instance of Sample that you create, so b will have a different true stored in it.
I have an object that looks like
var customObject = function() {
this.property = "value";
};
customObject.prototype = new otherObject();
customObject.prototype.property2 = function() {};
etc. - it's much bigger than this.
I can successfully instantiate the object by writing new customObject().
Now I would like to create a rather similar object, although a little different. This involves modifying certain properties and perhaps even adding or removing some. As in the above example, I would like it to be invokable by writing new customObject2().
I thought I could simply do:
var customObject2 = new customObject();
customObject2.prototype = customObject.prototype;
customObject2.property = "modified value";
etc.
However, when I try to instantiate it by doing new customObject2() I receive an error, stating that the customObject2 is not a function.
I hope I could illustrate well enough as to what pattern I desire to create. What approach should I take to create such a pattern?
If customObject is not a host object (i.e. won't give you an illegal invocation error if you try to call it differently to expected) you can apply the constructor to a different this Object;
var customObject2 = function () {
customObject.call(this); // construct as if `customObject`
// now do more stuff
this.anotherProperty = 'foo';
};
customObject2.prototype = Object.create(customObject.prototype);
// inherit prototype but keep original safe
new customObject2();
Backwards compatible Object.create
function objectWithProto(proto) {
var f;
if (Object.create) return Object.create(proto);
f = function () {};
f.prototype = proto;
return new f();
}
I think this should answer your question. Basically, the new keyword is returning an object and not a function.
Why are you not using the same formula you used the first time? For example:
var customObject2 = function(){};
customObject2.prototype = new customObject();
customObject2.property = "modified value";
new customObject2(); // works!
All properties of customObject will be inherited by the instances of customObject2 through the prototype chain.
I have an instance function in javascript and for naming conventions I have other instance function added as property of the first instance function object. It's better illustrated in the following working JavaScript.
var MyModule = (function() { // instance function
return function() {
console.log("ran MyModule");
}
}());
MyModule.RelatedModule = (function() { //second instance function is a property of first instance function object
return function() {
console.log("ran RelatedModule");
}
}())
var inst1 = new MyModule(), // logs "ran MyModule"
inst2 = new MyModule.RelatedModule(); // logs "ran RelatedModule"
This works as intended with no errors. What I'd like to do though is to create the function definition for MyModule after I've created the MyModule object, can anyone help me achieve this? I've illustrated my attempts below.
var MyModule = {}; // create object first, try to set a constructor on it later
MyModule.RelatedModule = (function() { // add properties to the MyModule object
return function() {
console.log("ran RelatedModule");
}
}())
// the following does not work, I'd like to set the `MyModule` constructor instance function and retain the `MyModule.RelatedModule` property
MyModule.constructor = (function() {
return function() {
console.log("ran MyModule");
}
}());
So, how do I retain the properties of an object and change it's constructor?
You're confusing a couple of concepts. In your first example, MyModule doesn't have a constructor, it is a constructor. That is, it's a function object that you intend to use with the new operator to create new objects. Those objects will have a constructor property that points back to MyModule (the function that created them). Changing this constructor property won't have any effect on MyModule; that property is just a pointer back to the function that instantiated the object.
In other words, you can't change MyModule's constructor. That's a meaningless statement.
Now, when you write:
var MyModule = {};
...you create a new object whose constructor property is Object():
console.log(MyModule.constructor) // prints Object()
Again, changing this property doesn't really do much (except obfuscate some useful book-keeping).
At this point MyModule is just a plain-old object. It's not a function at all. That's why you're getting the "not a function" error. Because it's not, but you're trying to use it as though it is. If you want that name to refer to a function (i.e. to a different object) then you're going to lose all references to any properties you previously set, because you're pointing at an entirely new object.
That's just the way it is.
Now, you could save a reference to the object that contains all those previously-set properties and copy them back into MyObject once you've pointed that name at a function. But I'm not sure what the point would be.
Everything lwburk says is correct, however, the below does what you were trying to accomplish, it does this by calling an init() method from MyModule.
var MyModule = function(){
return this.init();
};
MyModule.prototype.init = function(){};
MyModule.RelatedModule = (function() { // add properties to the MyModule object
return function() {
console.log("ran RelatedModule");
};
}());
MyModule.prototype.init = function(){
console.log("ran MyModule");
};
var inst1 = new MyModule(),
inst2 = new MyModule.RelatedModule();
First, there is a known browser bug where the constructor property (of the constructed object) correctly resolves using the prototype, but is not applied in object construction. So you need the following polyfill:
function NEW(clas, ...args)
{
let res = Object.setPrototypeOf({}, clas.prototype);
res.constructor.apply(res, args);
return res;
}
Second, you need to be setting MyModule.prototype.constructor instead of MyModule.constructor. The reason is that MyModule.constructor is the function that constructs new classes, not the function that constructs new objects. (See: Why does a class have a "constructor" field in JavaScript?)
In other words:
var MyModule = {}; // create object first, try to set a constructor on it later
MyModule.RelatedModule = (function() { // add properties to the MyModule object
return function() {
console.log("ran RelatedModule");
}
}())
// set the `MyModule` prototype.constructor instance function and retain the `MyModule.RelatedModule` property
MyModule.prototype = {
constructor() {
console.log("ran MyModule");
}}
var inst1 = NEW(MyModule), // logs "ran MyModule"
inst2 = NEW(MyModule.RelatedModule); // logs "ran RelatedModule"
The short answer is that you can't do that. You can however change the prototype of an object. Check out this answer for insight into how to rethink your approach to work with this constraint: Changing constructor in JavaScript
I'm trying to generate a class from an object in JavaScript. For example:
var Test = {
constructor: function() { document.writeln('test 1'); },
method: function() { document.writeln('test 2'); }
};
var TestImpl = function() { };
TestImpl.prototype.constructor = Test.constructor;
TestImpl.prototype.method = Test.method;
var x = new TestImpl();
x.method();
But this doesn't work: it'll only write 'test 2' (for whatever reason, constructor isn't being defined properly). Why?
I think you're doing it wrong.
Remember, JavaScript doesn't actually have classes at all. It has prototypes instead. So what you're really trying to do is create a prototype object that works like a collection of functions that you've built on another object. I can't imagine any useful purpose for this -- could you elaborate as to what you're trying to do?
Although I think you could make it work by using something like:
var TestImpl = function() {
Test.constructor.apply(this);
};
TestImpl.prototype.method = Test.method;
Your TestImpl function is the constructor. Usually you would do something like this:
var Test1 = function () {
document.writeln('in constructor');
};
Test1.prototype = {
x: 3,
method1: function() { document.writeln('x='+this.x); }
}
var y1 = new Test1();
y1.method1();
y1.x = 37;
y1.method1();
var y2 = new Test1();
y2.method1();
y2.x = 64;
y2.method1();
I think you have things a little backwards. Usually you will assign a prototype to a constructor, rather than assigning a constructor to a prototype.
The reason for assigning a method to the constructor's prototype, rather than to the "this" object inside the constructor, is that the former method creates only 1 shared function, whereas the latter method creates separate instances of a function. This is important (to keep memory allocation to a reasonable amount) if you create lots of objects each with lots of methods.
var Test = function () {
document.writeln('test 1');
this.method = function() { document.writeln('test 2'); }
};
var x = new Test();
x.method();
Javascript doesn't have a "Class" concept, It's all about prototype and the way you use them [ and you can simulate any kind of inheritance with this little neat feature. ]
In javascript "Function" plays the role of [ Class, Method and Constructor ].
so inorder to create "Class" behaviour in Javascript all you need to do is to use the power of "Function".
var A = function(){
alert('A.Constructor');
}
A.prototype = {
method : function(){
alert('A.Method');
}
}
var b = new A(); // alert('A.Constructor');
b.method(); // alert('A.Method');
now the neat thing about JS is that you can easily create "Inheritance" behaviour by using the same method. All you need to do is to connect the second class "Prototype Chain" to the first one, How?
B = function(){
this.prototype = new A(); // Connect "B"'s protoype to A's
}
B.prototype.newMethod = function() { alert('testing'); }
var b = new B();
b.method(); // Doesn't find it in B's prototype,
// goes up the chain to A's prototype
b.newMethod(); // Cool already in B's prototype
// Now when you change A, B's class would automatically change too
A.prototype.method = function(){ alert('bleh'); }
b.method(); // alert('bleh')
If you need any more references I suggest to take a look at Douglas Crockford's Site
Happy JS ing.