I try to override a method and script is:
function wrapper(target) {
target.doABC = function () {
alert('in wrapper');
};
return target;
}
function Model() {
wrapper(this);
}
Model.prototype.doABC = function () {
alert('in Model');
};
var a = new Model();
a.doABC();
The result is 'in wrapper'. I don't know why?
Any JavaScript object has own and inherited properties. Own are those defined directly on the instance and inherited are taken from the prototype object.
When using a property accessor, JavaScript first searches in object's own properties list. If the property is not found, it searches in object's prototype chain.
In your example, the wrapper() method defines on object instance an own property doABC, which is a function that alerts 'in wrapper'. Even if the object has a prototype with the same property doAbc that alerts 'in Model', JavaScript anyway will use the own property.
function wrapper(target) {
// Define an own property "doABC"
target.doABC = function () {
alert('in wrapper');
};
return target;
}
function Model() {
wrapper(this);
}
// Define an inherited property "doABC"
Model.prototype.doABC = function () {
alert('in Model');
};
var a = new Model();
//Use the own property "doABC". The inherited "doABC" is ignored.
a.doABC();
As an addition, the own property can be removed using delete operator. After deletion, the object will use the inherited property.
// delete the own property "doABC"
delete a['doABC'];
// the inherited "doABC" will be used. Alerts "in Model"
a.doABC();
Check the complete working demo.
Let me see if I can explain:
You have two separate versions of doABC here.
Your target.doABC creates a function specific to that instance of your Model and each Model get its own doABC.
Because Model has a doABC, the JavaScript engine has no need to look 'up the chain' for something else, hence it will never look for the Model.prototype.doABC version.
You can see this by adding these lines:
Model.prototype.doXYZ = function () {
alert('in Model');
};
and calling
a.doXYZ();
Since a doesn't have its own doXYZ then, and only then, will it look up the chain and see the method in the prototype.
Related
Say I have a constructor function in JavaScript, which I use to create my objects. How would I alter the "contents" of all the objects created by this function through a method call from this function. What I am wondering is, weather it is possible to invoke a method call upon the prototype, like we'd modify the prototype adding our own methods/properties.
For example:
function MyConstructor()
{
var privateVariable = "This is an ORIGINAL private variable";
this.publicVariable = "This is public";
this.modificationMethod = function(){
// I want to call this methode on the prototype
privateVariable = "I am now changed";
};
this.alertMe = function(){
alert(privateVariable);
};
}
var a = new MyConstructor();
a.alertMe(); // alerts This is an ORIGINAL private variable
a.modificationMethod();
a.alertMe(); // alerts I am now changed
This works when I want to change a single object, I invoke the method, it changes that single object. However, I want to change all the objects that are created by the constructor.
I know I can add new methods to it like this:
MyConstructor.prototype.foo = function(){
alert("foo");
}
a = new MyConstructor();
a.foo();
But it does not let me run the existing methods to change the properties, and throws an error:
MyConstructor.prototype.modificationMethod();
"modificationMethod is not a function"
EDIT: Updating the answer to reflect everything discussed in comments. I initially misunderstood the OP's issue.
Every object is linked to a prototype object. When trying to access a property that does not exist, JavaScript will look in the object's prototype object for that property and return it if it exists.
The prototype property of a function constructor refers to the prototype object of all instances created with that function when using new.
What that means is that prototype object is sort of a fallback mechanism when an object itself does not have the desired property.
The concept of private variables are in fact closures.
Prototype functions are defined outside of the constructor function scope, meaning they cannot access the "private properties".
However, it is possible to assign a closure to the prototype property itself, effectively making a private shared (static) variable.
function MyConstructor() {};
MyConstructor.prototype = (function() {
var extensions = {
foo: null,
test: function() {
alert("Test was extended");
}
};
return {
registerExtension: function(name, callback) {
extensions[name] = callback;
},
// in order to use the extensions object, you need a generic function such as invoke
invoke: function(name) {
if (typeof extensions[name] === 'function')
extensions[name].call(this);
}
};
}());
var a = new MyConstructor();
a.invoke('test'); //will alert
a.invoke('foo'); //will not alert (not a function)
a.registerExtension('foo', function() {
alert("foo is now extended as well");
});
a.invoke('test'); //will alert
a.invoke('foo'); //will alert
A simpler approach, if you don't mind for the extended functions to be visible (public), would be to directly extend the prototype.
function MyConstructor() {};
MyConstructor.prototype = {
foo: null,
test: function() {
alert("Test was extended");
}
};
var a = new MyConstructor();
a.test(); //will alert
//a.foo(); //will not alert (not a function)
MyConstructor.prototype.foo = function() {
alert("foo is now extended as well");
};
a = new MyConstructor();
a.test(); //will alert
a.foo(); //will alert
You can easily create an interface for prototype extension.
Object.prototype.registerExtension = function( name, func ){
this.prototype[ name ] = func;
};
// ...
MyConstructor.registerExtension( 'foo', function() {
alert("foo is now extended as well");
} );
I am learning javascript and would love help understanding the snippet of code.
From Object.DefineProperties definition, the first parameter is an object. Is MyObjectConstructor a declaration or an object. With a constructor function I would expect to call new to make it an object.
This is what is confusing me. Or as I read in Javascript functions are objects so do I treat it as an object and the this property is where all staticProps and instanceProps are added to?
var _prototypeProperties = function (child, staticProps, instanceProps) {
if (staticProps){
Object.defineProperties(child, staticProps)
};
if (instanceProps) {
Object.defineProperties(child.prototype, instanceProps);
}
};
function myFunction() {
function MyObjectConstructor(element) {
this.element = element;
this.initialized = false;
}
_prototypeProperties(MyObjectConstructor, {...}, {...});
}
Yes, (constructor) functions are objects as well in javascript, and you can add properties directly to them.
The _prototypeProperties function in your example snippet does put the staticProperties on the constructor, so that they could be accessed as MyObjectConstructor.myStaticProperty. It also does put instanceProps (better: "class properties", "prototype properties") on the MyObjectConstructor.prototype object, from where they are inherited by instances: (new MyObjectConstructor).myPrototypeProperty. Lastly, your MyObjectConstructor does put "real" (own) properties on the instances, specifically (new MyObjectConstructor).element and .initialised.
In JavaScript, once defined, the resulting functions act identically:
function Hat() { }
var Hat = function() { }
Conventionally the first is used to create objects (usually with new) and the second is used as a regular method.
The new operator, when preceding a function gets kinda weird. Using the new operator will:
create a new Object "it"
set the function being called as "it"s prototype
binds "it" to this within the function
overrides the return value of the function with "it". This overrides both explicit returns and implicit returns of undefined.
For example:
// first define Hat function
function Hat() { this.color = 'red' }
// calling with `new` implicitly returns a new object bound to the function
new Hat()
// > Hat { color: "red" }
// invoking without `new` implicitly returns `unefined`,
// but `this` points to Hat's parent object.
// If running in the browser, Hat's parent object would be `window`
// so now Window.color is set to "red"
Hat()
//> undefined
Window.color
//> "red"
Be careful with new, because the new object will be returned instead of any explicit returns.
var color = function() { return "blue" }
color()
//> "blue"
new color()
//> color {}
JavaScript is prototypal by nature. The new operator reflects neither prototypical nor classical inheritance. I avoid it when possible, although many popular libraries use it.
I recommend reading through Crockford's explanation of JavaScript's prototypal inheritance: http://javascript.crockford.com/prototypal.html
Its terse, but if you understand his 10 lines of demo code you'll be good.
Play with bind, call and apply, and different scoping contexts too. After understanding scoping and the prototypal nature, the rest is just syntax.
first : the function is the first type object in the javascript . it means you can deliver the function as value . for example :
function test(){
return function(){
console.log('function');
}
}
test()();
you return the function as return an object , function can be assigned and the function another kind of value !
var test = function(i) {
// body...
return i;
}
test('123');
a character string 'test' refer to a Anonymous function , you can understand that you transmit a function to a character string .
second : if you use new to create a instance via function , this function will be called construction function , normally it used to init the params , and the instance will take the construction function own property or method and prototype's property or method from the construction function .
third : the instance's property of "__proto__" is refer to the construction function's prototype object . this is why the instance can use the prototype's property or method from the construction function .
forth : if you create the instance by new , the this will refer to the instance object ! so that instance can use the property and method .
from your code :
var _prototypeProperties = function (child, staticProps, instanceProps) {
if (staticProps){
Object.defineProperties(child, staticProps)
};
// the properties from the own construction function , like this :
// this.element = element;
// this.initialized = false;
if (instanceProps) {
Object.defineProperties(child.prototype, instanceProps);
}
};
// the properties from the construction function's prototype object . like this :
// MyObjectConstructor.prototype.name = 'somebody';
// MyObjectConstructor.prototype.getName = function(){
// return this.name;
// }
I am trying to create a JavaScript library of UI components that are commonly used by the projects in my group. I have the following code to define the library.
var libName = function() {
var _libName = this;
_libName.componentName = function () {
// Some Private Variables
var _componentName = function (args) {
// Construct the object...
};
_componentName.addObject = function (args) {
// Add an object...
};
_componentName.removeObject = function (args) {
// Remove an object...
};
return _componentName;
}();
return _libName;
}();
Now, when I use this in a page to create the component I call the following code.
var component = new libName.componentName(args);
It initializes just fine and creates the base component that I expect. Now I want to add some data to the component, so I call the following function.
component.addObject(someObject);
But instead of calling the function like I expect it to, it says that the component object does not have a property 'addObject'. I looked into this with the following code.
if (libName.componentName.addObject) {
console.log("libName.componentName.addObject exists"); // Logs
}
if (component.addObject) {
console.log("component.addObject exists"); // Doesn't log
}
if (component.constructor.addObject) {
console.log("component.constructor.addObject exists"); // Logs
}
So my question is what exactly is going on here? Why does an object, in this case component, not have access to the properties/functions I expect it to? Does this have something to do with the fact that I am using memoized closures to define the library? How do I make it so that an object initialized from this library has access to these properties/functions?
Use the prototype of the function to define instance methods :
_componentName.prototype.addObject = function (args) {
// Add an object...
};
_componentName.prototype.removeObject = function (args) {
// Remove an object...
};
your script doesnt work because you are calling _componentName properties , that are not passed to instances of _componentName if defined directy on the object. Remember using new mean using prototypal inheritance. Javascript doesnt have class based inheritance.
When trying to test prototype functionality, I got this odd result:
Here is my first test:
<script>
function Hello() {
}
var a = new Hello();
Hello.prototype.name = "Fred";
alert(a.name);
</script>
And, here's the second one:
<script>
function Hello() {
}
var a = new Hello();
Hello.prototype = {
name : "Fred",
}
alert(a.name);
</script>
I can't understand why the first will return a alert with "Fred" and the second is "undefined" though these mean the same thing?
Could you help me with it?
Thank you.
When you define a function in JavaScript, the interpreter makes a special prototype property available on the function, which points to an object, in case you use that function as a constructor. The [[Prototype]] internal property points to this object when you create a new object using the constructor.
When you replace the prototype property with a new one, you are replacing that reference, and if you do it after you instantiate an object, you will find the prototype object appears to be stale (that object's [[Prototype]] is pointing to the original object that prototype pointed to).
Solutions
Only assign new properties directly on the prototype property.
var constructor = function() { };
constructor.prototype.someMethod = function() { };
Use an extend type function to extend the existing prototype property with your new object (in this example, I used Underscore's extend() function).
var constructor = function() { };
_.extend(constructor.prototype, { someMethod: function() { } });
Make sure after the constructor, assigning the prototype property is the very next step in your program (generally not recommended).
var constructor = function() { };
constructor.prototype = { someMethod: function() { } };
Your ordering is messed up. You need assign the object to the prototype before using the new operator:
function Hello() {
}
Hello.prototype = {
name : "Fred",
}
var a = new Hello();
alert(a.name);
Demo.
The two code snippets are not actually equal.
In the first script you only override Hello.prototype.name, while in the second script you override the whole content of Hello.prototype.
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