Javascript passing object as function parameter - javascript

I'm quite new to javascript, so maybe it's a silly error.
I created an object like the follwing:
function objA(){
this.prop1;
this.prop2;
this.prop3;
this.func1=function(){
alert('func1');
}
this.func2=function(){
alert('func2');
}
}
I now have a function where I want to pass the object:
var foo=new objA;
function test(foo){....}
The problem is that when I call test(), I get the functions in objA (objA.func1 and objA.func2) executed.
I would like just to get the properties value of objA.
I have to use another function and an array, fill the array with the properties of objA and then pass the array:
var arrayA={}
function fillArray(data){
arrayA.prop1=data.prop1;
arrayA.prop2=data.prop2;
arrayA.prop3=data.prop3;
}
function test(arrayA){....}
Is it the only way or I'm doing something wrong ?

Functions are properties of an object (they are first-class values), and thus they show up in for (var propName in myObj) loops like any other property. You can avoid examining them further via:
for (var prop in myObj){
if (!myObj.hasOwnProperty(prop)) continue; // Skip inherited properties
var val = myObj[prop];
if (typeof val === 'function')) continue; // Skip functions
// Must be my own, non-function property
}
Alternatively, in modern browsers you can make specific properties (like your functions) non-enumerable, so they won't show up in a for ... in loop:
function objA(){
this.prop1 = 42;
Object.defineProperty(this,'func1',{
value:function(){
...
}
});
}
For more on this, see the docs for Object.defineProperty or Object.defineProperties.
Finally, if you don't need to define your functions as closures you can define them on the prototype of your object in which case the hasOwnProperty test will cause them to be skipped:
function objA(){
this.prop1 = 42;
}
objA.prototype.func1 = function(){
// operate on the object generically
};
var a = new objA;
"func1" in a; // true
a.hasOwnProperty("func1"); // false

Related

Can object method have own propertis?

For function I can make this:
uniqueInteger.counter = 0;
function uniqueInteger() {
return uniqueInteger.counter++; // Increment and return counter property
}
Can I do this also with object method?
Yes, you can, because functions are first class objects:
In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.
var object = {
x: function () { return this.x.value; }
};
object.x.value = 42;
document.write(object.x());
Objects methods are functions. You can do this for any function:
var a = function () { }
a.bar = "f";
for(property in a) {
console.log(a[property]);
}
// outputs f
However, please note that "own property" has a specific meaning in javascript, to the point that it's highly recommended to check if a property is object's own property when iterating through the properties (e.g. to ignore inherited properties).
o = new Object();
o.prop = 'exists';
o.hasOwnProperty('prop'); // returns true
o.hasOwnProperty('toString'); // returns false
o.hasOwnProperty('hasOwnProperty'); // returns false

Once again: JS functions and objects

So I am reading up on JS with Programming JS applications and JS the goodparts. Reading through objects and functions.. which are apparently the same. According to Crockford himself (and practically everybody). But then I ask: if they are the same then why if I have an object:
var myObject = {
value: 0,
increment: function (inc) {
this.value += inc;
}
};
I can add a function like so:
myObject.double = function () {
this.value += this.value;
}
But when I have a constructor (a function..) :
var myConstructor = function() {
this.value = 0;
this.increment = function(inc){
this.value += inc;
};
};
I cannot add a function like this:
myConstructor.double = function(){
this.value += this.value;
};
But only over the prototype like this:
myConstructor.prototype.double = function(){
this.value += this.value;
};
Now how can anybody say that object and function are the same??
Interestingly, the assignment of the "double" method to the constructor does not give an error, only when you create an object afterwards with new and call the double method on this object does it give: "TypeError can not find".
Also, console.log on the constructor gives:
{ [Function] double: [Function] }
Notice the missing comma between "[Function]" and "double" by the way.. But this probably shows that really functions are actually objects because we just added the double property (a function) to this object.
But then the question becomes... why can I call new on myConstructor and not on myObject ?? How does JS distinguish between them? If they are both objects which can consists of properties, values and functions..?
EDIT: ok, so I get they are not the same, sorry for my imprecise wording. But one question remains: how does JS know the difference between an object with a function property and a constructor to which properties have been added?
var object = {
property : "value",
method: function(){
}
};
console.log(object) outputs to:
{ property: 'asdf', method: [Function] }
and
var myConstructor = function() {
this.property = "value";
this.method = function(inc){
};
};
myConstructor.property = "value";
console.log(myConstructor) outputs to:
{ [Function] property: 'value' }
So if an object has an anonymous function JS knows its a constructor? Or does it know that over the prototype maybe?
How does JS know the difference between an object with a function
property and a constructor to which properties have been added?
There are different terminologies:
Functions are objects which are Function instances.
Callable objects are objects with an internal [[Call]] method.
Constructors are objects with an internal [[Construct]] method.
Usually they coincide, so it's usual to call them all functions.
Then it's easy:
If you attempt to call an object and it has a [[Call]] method, that method will be called. Otherwise it's not callable, so error.
If you attempt to instantiate an object and it has a [[Construct]] method, that method will be called. Otherwise it's not a constructor, so error.
Moreover, there is the [[Class]] internal property, which for functions is usually "Function".

object in prototype is inherited as reference

I want to inherit new object instance using prototype.
Test case:
var MyObj = function() {}
MyObj.prototype.objName = {}
// I want this to be a different object for each instance of MyObj
var o1 = new MyObj (),
o2 = new MyObj ();
o1.objName['a'] = 1;
o2.objName['a'] = 2;
alert(o1.objName['a']) // 2
alert(o1.objName === o2.objName) // true
This means that objects in prototype are not inherited as its copies but instead as its reference.
I know that normally you can do it like this.
var MyObj = function() {
this.objName = {}
}
var o1 = new MyObj(),
o2 = new MyObj();
alert(o1.objName === o2.objName) // false
This works fine, but in my case this is not an option. I really need to define objName outside the MyObj function.
I managed to "solve" the problem with this
MyObj.prototype.objName = function() {
if ( this._objName === undefined ) {
this._objName = {};
}
return this._objName;
}
var o1 = new MyObj(),
o2 = new MyObj();
o1.objName()['a'] = 1;
o2.objName()['a'] = 2;
alert(o1.objName()['a']) // 1
But this is not very pretty and the performance of this code is much worse.
Is there any way to solve this more elegantly ?
This means that objects in prototype are not inherited as its copies but instead as its reference.
Nothing on the prototype is copied - the whole concept of prototypical inheritance is that properties reference the shared properties of the prototype object. So if you want a property to be individual for each instance, you have to explicitly assign it to the object and shadow the prototype property; just as you're doing it with the _objName property in your code.
But this is not very pretty and the performance of this code is much worse.
If you want it pretty, move it to the constructor (or make the constructor look for something like an init method to call if exists, then you can create that init method on the prototype.
To make performance a little better, you can change the getter function to
MyObj.prototype.getObj = function() {
var obj = {};
this.getObj = function(){ return obj; }; // overwrite itself
return obj;
};
though it still has the function call overhead. For even more elegance, you can use a getter property (not supported in old browsers) that removes itself on the first access:
Object.defineProperty(MyObj.prototype, "objName", {
get: function() {
var obj = {};
Object.defineProperty(this, "objName", {
value: obj,
writable: true //?
});
return obj;
},
enumerable: true,
configurable: true
});
Now you can omit the function call parenthesis.
This means that objects in prototype are not inherited as its copies but instead as its reference.
Just to be clear. First of all in JavaScript all objects are passed by reference, not by value. Only primitives are passed by value.
Second, you're not actually "copying" or "passing" anything. When you set a prototype, you're creating a prototype's chain. It means that in your case:
var MyObj = function() {};
MyObj.prototype.objName = {} ;
var o1 = new MyObj ();
var o2 = new MyObj ();
Both o1 and o2 doesn't have any property called objName, and you can simply test it with:
console.log(Object.keys(o1)); // []
When JS see a code like o1.objName, as first thing checks if the object has this property, and if it has, use it. If not, start to looking in the prototype's chain, starting by the prototype of o1, that is MyObj.prototype: it found the properties objName, and returns it. If it didn't find it, then JS will continue to check the prototype of MyObj.prototype, and so on. So, here the point: MyObj.prototype it's an object: and you shared that object between o1 and o2. That's why the instance of objName is the same. It's exactly the same logic of having:
function objName(obj) {
return "objName" in obj ? obj.objName : O.objName;
}
var O = { objName: [] };
var foo = {};
var bar = {};
objName(foo).push(0);
objName(bar).push(1);
So, you can't put in prototype any object that is not meant to be shared across the objects creates using that prototype. I would say that shared states like that is also a bad practice that should be avoided, that's why in general prototype shouldn't have such property.
It's still not clear to me why you can't modify the constructor, but the point is: when you create the instance of your object, you have to "setup" it. Usually, calling the constructor, but any function is fine. This is made also when you want to support inheritance, and calling the "super" constructor to initialize your object.

Making primitive data types readOnly/nonConfig in JavaScript

Does anyone have any example implementation of making individual object props readOnly/non-configurable? I mean primitive data types. Have tried using ES5 Object API, but hitting a brick wall.
I can't show code, because it's still at that "messy" phase, but basically I'm iterating through an outside object which, itself, holds numeruos objects. Those objects each hold various primitive data types. I have made the outer objects readOnly, non-config, etc, but can't figure out how to do likewise for individual props, the innermost props.
So, if outer.inner.prop === "Hello", I want to make that value readOnly.
Thanks!
UPDATE
I just figured this out, it was all in the for loop I was using to iterate over props. Now I've actually get data descriptors for the props, even the primitive ones. :) Thanks all!
You have to iterate through the inner object, since there is no way to deep-freeze an object using standard ES5 methods.
function deepFreeze(obj) {
Object.keys(obj).forEach(function (key) {
if (typeof obj[key] == 'object')
deepFreeze(obj[key]);
});
Object.freeze(obj);
}
Edit:
Also works for defineProperty if you don't want to freeze:
function deepWriteProtect(obj) {
Object.keys(obj).forEach(function (key) {
if (typeof obj[key] == 'object')
deepWriteProtect(obj[key]);
Object.defineProperty(obj, key, { writable: false });
});
}
I'm not 100% sure I understand your question correctly, but from what I gather you are asking for private variables. If so, that can be easily achieved using closures.
function myClass(){
var mySecretProperty = 10;
this.getMySecretProperty = function(){
return mySecretProperty;
}
this.changeMySecretProperty = function(s){
// whatever logic you need for a setter method
mySecretProperty = s;
}
}
var myObj = new MyClass();
myObj.changeMySecretProperty(120);
myObj.getMySecretProperty(); // will return 120
myObj.mySecretProperty // will return undefined
Would the following (ES5) example help? It creates an empty constructor, with a getter for property a (and no setter, so de facto a is read only):
var Obj = function(){};
Obj.prototype = {
get a() {return 5;}
}
var x = new Obj;
alert(x.a); //=> 5
x.a = 6; //=> TypeError: setting a property that has only a getter
Not using ES5 you can do
var Obj = function(){
var a = 5;
if (!Obj.prototype.getA) {
Obj.prototype.getA = {
toString: function() {
return a;
}
};
}
}
var y = new Obj;
alert(y.getA); //=> 5
But that is not 100% failsafe: Obj.prototype.getA can be overwritten.
Here is a jsfiddle showing how you can use ES5 getter/setter definitions to make a property of an object something that can only be fetched. The code looks like this:
var object = {
get x() {
return 17;
}, set x() {
alert("You cannot set x!");
}
};
Of course the getter could obtain the value of the property ("x") from anywhere, like a closure from a constructor or something. The point is that the setter simply does not change the value, so attempts to change it:
object.x = 100;
will not have any effect.

prototype and constructor object properties

I've:
function Obj1(param)
{
this.test1 = param || 1;
}
function Obj2(param, par)
{
this.test2 = param;
}
now when I do:
Obj2.prototype = new Obj1(44);
var obj = new Obj2(55);
alert(obj.constructor)
I have:
function Obj1(param) {
this.test1 = param || 1;
}
but the constructor function has been Obj2... why that?
Obj1 has become the Obj2 prototype...
Can someone explain me, in detail, the prototype chain and the constructor property
Thanks
constructor is a regular property of the prototype object (with the DontEnum flag set so it doesn't show up in for..in loops). If you replace the prototype object, the constructor property will be replaced as well - see this explanation for further details.
You can work around the issue by manually setting Obj2.prototype.constructor = Obj2, but this way, the DontEnum flag won't be set.
Because of these issues, it isn't a good idea to rely on constructor for type checking: use instanceof or isPrototypeOf() instead.
Andrey Fedorov raised the question why new doesn't assign the constructor property to the instance object instead. I guess the reason for this is along the following lines:
All objects created from the same constructor function share the constructor property, and shared properties reside in the prototype.
The real problem is that JavaScript has no built-in support for inheritance hierarchies. There are several ways around the issue (yours is one of these), another one more 'in the spirit' of JavaScript would be the following:
function addOwnProperties(obj /*, ...*/) {
for(var i = 1; i < arguments.length; ++i) {
var current = arguments[i];
for(var prop in current) {
if(current.hasOwnProperty(prop))
obj[prop] = current[prop];
}
}
}
function Obj1(arg1) {
this.prop1 = arg1 || 1;
}
Obj1.prototype.method1 = function() {};
function Obj2(arg1, arg2) {
Obj1.call(this, arg1);
this.test2 = arg2 || 2;
}
addOwnProperties(Obj2.prototype, Obj1.prototype);
Obj2.prototype.method2 = function() {};
This makes multiple-inheritance trivial as well.
Check out Tom Trenka's OOP woth ECMAscript, the "Inheritance" page. Everything from the prototype is inherited, including the constructor property. Thus, we have to unbreak it ourselves:
Obj2.prototype = new Obj1(42);
Obj2.prototype.constructor = Obj2;
Short version: ‘constructor’ doesn't do what you think, and isn't cross-browser compatible. Never use it.
Long version: Convention for prototype inheritance in JavaScript
Generally: you're getting confused due to (a) the impedence mismatch between class-based and prototype-based OO, and (b) the strangeness of JavaScript's particular rather poor interpretation of prototype-based OO.
You'll probably be happier if you find one classes-in-prototypes implementation you like and stick with that. Many libraries have one. Here's an arbitrary one I use:
Function.prototype.subclass= function() {
var c= new Function(
'if (!(this instanceof arguments.callee)) throw(\'Constructor called without "new"\'); '+
'if (arguments[0]!==Function.prototype.subclass.FLAG && this._init) this._init.apply(this, arguments); '
);
if (this!==Object)
c.prototype= new this(Function.prototype.subclass.FLAG);
return c;
}
Function.prototype.subclass.FLAG= new Object();
And here's an example of how one might use it:
// make a new class
var Employee= Object.subclass();
// add members to it
Employee.prototype._LEGS= 2;
Employee.prototype.getLegs= function() {
return this._LEGS;
};
// optional initialiser, takes arguments from constructor
Employee.prototype._init= function(name) {
this.name= name;
};
// make a subclass
Manager= Employee.subclass();
// extend subclass method
Manager.prototype._init= function(name, importance) {
// call base class's method
Employee.prototype._init.call(this, name);
this.importance= importance;
}
// all managers are well-known to have three legs
Manager.prototype._LEGS= 3;
// create one
var jake= new Manager('Jake the Peg', 100);
Well, the constructor property is a property like any other, on the prototype (property) of Obj1. If you understand how prototypes work, this might help:
>>> obj.hasOwnProperty("constructor")
false
// obj's [[Prototype]] is Obj2.prototype
>>> Obj2.prototype.hasOwnProperty("constructor")
false
// Obj2.prototype's [[Prototype]] is Obj1.prototype
>>> Obj1.prototype.hasOwnProperty("constructor")
true
// Oh?
>>> Obj1.prototype.constructor
Obj1()
Aha! So obj has no constructor, JS goes to get it up the [[Prototype]] chain, all the way from Obj1.prototype.constructor
I'm not sure why the constructor property isn't just set on an object when you use `new'. There might be a reason, or it might just be an oversight. Either way, I tend to avoid it.

Categories

Resources