hasOwnProperty in JavaScript - javascript

Consider:
function Shape() {
this.name = "Generic";
this.draw = function() {
return "Drawing " + this.name + " Shape";
};
}
function welcomeMessage()
{
var shape1 = new Shape();
//alert(shape1.draw());
alert(shape1.hasOwnProperty(name)); // This is returning false
}
.welcomeMessage called on the body.onload event.
I expected shape1.hasOwnProperty(name) to return true, but it's returning false.
What is the correct behavior?

hasOwnProperty is a normal JavaScript function that takes a string argument.
When you call shape1.hasOwnProperty(name) you are passing it the value of the name variable (which doesn't exist), just as it would if you wrote alert(name).
You need to call hasOwnProperty with a string containing name, like this: shape1.hasOwnProperty("name").

hasOwnProperty expects the property name as a string, so it would be shape1.hasOwnProperty("name")

Try this:
function welcomeMessage()
{
var shape1 = new Shape();
//alert(shape1.draw());
alert(shape1.hasOwnProperty("name"));
}
When working with reflection in JavaScript, member objects are always refered to as the name as a string. For example:
for(i in obj) { ... }
The loop iterator i will be hold a string value with the name of the property. To use that in code you have to address the property using the array operator like this:
for(i in obj) {
alert("The value of obj." + i + " = " + obj[i]);
}

hasOwnProperty() is a nice property to validate object keys.
Example:
var obj = {a:1, b:2};
obj.hasOwnProperty('a') // true

Related

Using a string stored in a variable as a name for another variable

I want to concatenate a string passed as argument with another word and then use it as a variable name for an array. Is this allowed?
function getFromSomewhere(arg1) {
string newName = arg1 + "sampleWord";
var (use NewName here) = [];
}
Not allowed, unfortunately. Variable names, such as newName, that we see are rid of at compilation time for optimization. Your machine will have no use for it's name newName during runtime, which is when you're trying to assign the name to it.
You could use an object with the wanted fruits as key for the array, like in the example.
The object is easy to access and to maintain.
var array = ["apple", "banana", "grapes"],
prices = {};
array.forEach(function (k) {
prices[k] = [];
});
prices.apple.push(1, 10, 3);
console.log(prices.apple[2]);
console.log(prices);
You can use newName as the name of a property
function getFromSomewhere(arg1) {
var myVariableNamedAtRuntime = [];
string newName = arg1 + "sampleWord";
myVariableNamedAtRuntime[newName] = [];
}
and then access the array as ...
myVariableNamedAtRuntime[newName]
There is no way you can add new variables to the function definition after the function is defined.. However you can always add new properties to the function object defined or it's prototype and you can access them as follows;
function getFromSomewhere(arg1) {
var newName = arg1 + "_sampleWord_";
this.getFromSomewhere.varName = newName + "test";
this.getFromSomewhere.prototype.varName = newName + "best";
console.log(this.getFromSomewhere.varName);
console.log(this.getFromSomewhere.prototype.varName);
}
getFromSomewhere("test");
You can add the variable to the window object:
function getFromSomewhere(arg1) {
var newName = arg1 + "sampleWord";
window[newName] = [];
}
getFromSomewhere("blip");
console.log(blipsampleWord); // You'd get []
Yes it is possible. But no, you dont want to do that. Dynamic variable names are always a sign, that you should use an object instead. In this case i think you could simply map your array of strings to an array of objects:
function namesToObj(arr){
return arr.map( name => ({
name,
price:10
}));
}
namesToObj(["banana","tomato"])
/*results in
[{name:"banana",price:10},{name:"tomato",price:10}]
*/

JavaScript - Iterating through objects in instance of object 'class'

I'm trying to iterate through all objects inside the instance of an object using pure JavaScript.
I tried something like this:
function a(){
this.iterate = function(){
for (var obj in this){
console.log(obj);
}
}
}
var A = new a();
A.insertedValue = 20;
A.iterate();
When doing this, instead of logging for example "20" for insertedValue it simply logs the name of the variable like "insertedValue".
Is there either a better way of looping through all objects in an instance of a object or a way to get the values from the objects I'm looping through?
Is there either a better way of looping trough all objects in an
instance of a object or a way to get the values from the objects I'm
looping trough?
Because you are simply printing the key inside this rather than its value using this[obj].
Make it
function a(){
this.iterate = function(){
for (var obj in this){
console.log(this[obj]); //observe that this line has changed
}
}
}
The way you're doing it is largely correct, it's just that for-in loops through the names of the object's properties, not their values. So to output the property's value, you use this[name]:
function a(){
this.iterate = function(){
for (var name in this){
console.log(name + "=" + this[name]);
}
};
}
Note that for-in will loop through the enumerable properties of the object, including ones it inherits from its prototype. If you just want own properties, and not inherited ones, you can either check whether the property is an "own" property through hasOwnProperty:
function a(){
this.iterate = function(){
for (var name in this){
if (this.hasOwnProperty(name)) {
console.log(name + "=" + this[name]);
}
}
};
}
Or use the handy Object.keys, which gives you an array of own enumerable properties:
function a(){
this.iterate = function(){
Object.keys(this).forEach(function(name) {
console.log(name + "=" + this[name]);
});
};
}

Concatenating chosen random property to object to get the array?

I have an object with a few arrays in it. I am trying to return one of the arrays randomly. I have a function that returns one of the properties in the object, but I am not sure how to use it when concatenating it to the object name. For example:
Object:
var myObj = {
itemOne:['blue','red','green'],
itemTwo:['sky','grass','book'],
itemThree:['day','month','year']
}
To get a certain array I would do myObj.itemOne which will return the first array. But I want to randomly return an array. I have a function that will return itemOne, itemTwo, or itemThree randomly, but when concatenating what the function returns with myObj. it does not work. What can I do. Here is the function:
function pickRandomProperty(myObj) {
var result;
var count = 0;
for (var prop in myObj){
if (Math.random() < 1/++count){
result = prop;
}
}
return result;
}
var getItemInObject = pickRandomProperty(myObj);
Using what getItemInObject returns, I try to concatenate it with myObj to return the array. How would I do that? Here is what I have tried:
var getItemInObject = pickRandomProperty(myObj);
var randProp = myObj.getItemInObject;
or even:
var randWord = myObj + '.' + getItemInObject;
Which returns '[object Object].itemTwo'
Here is a fiddle: http://jsfiddle.net/xrk7b4zs/
Thanks for any help
You use brackets notation:
var getItemInObject = pickRandomProperty(myObj);
var randProp = myObj[getItemInObject];
// ^ ^
In JavaScript, you can refer to a property using dot notation and a property name literal (obj.foo), or brackets notation and a property name string (obj["foo"]) (or Symbol in ES6+, but that's not relevant here). In that second case, the string can be the result of any expression, including a variable reference.
Live Example:
var myObj = {
itemOne:['blue','red','green'],
itemTwo:['sky','grass','book'],
itemThree:['day','month','year']
}
function pickRandomProperty(myObj) {
var result;
var count = 0;
for (var prop in myObj){
if (Math.random() < 1/++count){
result = prop;
}
}
return result;
}
var getItemInObject = pickRandomProperty(myObj);
var array = myObj[getItemInObject];
document.body.insertAdjacentHTML(
"beforeend",
"<pre>" + JSON.stringify(array) + "</pre>"
);
Side note: There's a much easier way to pick a random property, assuming you only care about the object's "own" properties (not ones from its prototype):
function pickRandomProperty(myObj) {
var keys = Object.keys(myObj);
return keys[Math.floor(Math.random() * keys.length)];
}
Live Example:
var myObj = {
itemOne:['blue','red','green'],
itemTwo:['sky','grass','book'],
itemThree:['day','month','year']
}
function pickRandomProperty(myObj) {
var keys = Object.keys(myObj);
return keys[Math.floor(Math.random() * keys.length)];
}
var getItemInObject = pickRandomProperty(myObj);
var array = myObj[getItemInObject];
document.body.insertAdjacentHTML(
"beforeend",
"<pre>" + JSON.stringify(array) + "</pre>"
);
You can concatanate strings, not code. To access an object property from a variable, use the bracket notation:
var randWord = myObj[getItemInObject];
http://jsfiddle.net/xrk7b4zs/2/
However, even this code will only return the object property which is an array of strings, and judging by your variable name, you might want to pick a random string from that array.
note: if for some reason you have to go with the dot notation, you can evaluate the concatted string using eval but it's not recommended in +99% of cases.
var getItemInObject = pickRandomProperty(myObj);
console.log(getItemInObject)
var randWord = myObj[getItemInObject];
You need to do myObj[getItemInObject];
Upadated Fiddle
You can use eval that evaluates string as javascript code :
var randWord = eval('myObj.' + getItemInObject);
Working Fiddle
you can Achieve the Object Property by two Way
using "." operator and 2. using passing key String in [""].
You used in your code here :
var myObj = {
itemOne:['blue','red','green'],
itemTwo:['sky','grass','book'],
itemThree:['day','month','year']
}
you can get your Object Property value by two ways here
1. myObj.itemOne // this way you used when you know what value you want to return.
2. myObj["itemOne"] // this way you will used when you want to access you object Property in generic Way. i recommend you to use this way.
In your code:
var getItemInObject = pickRandomProperty(myObj);
this variable contained your give your object.property name which is you return by running Function.
var getItemInObject = pickRandomProperty(myObj);
So You can pass this variable Like This for accessing randomly your object property value
var randWord = myObj[getItemInObject];
console.log(randWord);
I hope this Answer will help you to achieve which you want. it will give you result like.:
var myObj = {
itemOne:['blue','red','green'],
itemTwo:['sky','grass','book'],
itemThree:['day','month','year']
}
function pickRandomProperty(myObj) {
var result;
var rKey = Math.floor((Math.random()*3)+1) -1;
return myObj.itemOne[rKey];
}
var getItemInObject = pickRandomProperty(myObj);
var randWord = 'myObj.itemOne' + '.' + getItemInObject;
console.log(randWord);
It works!!!

ask for a method in javascript prototype

i have one question, i have this class in javascript:
//FactVal
UTIL.Classes.FactVal = function(entity, attribute, value) {
this.entity = entity;
this.attribute = attribute;
this.value = value;
}
UTIL.Classes.FactVal.prototype.setEntity = function(entity) {
this.entity = entity;
}
When im serializing a json string to an object of this type, i want to ask if exists the setEntity method, i have this json:
"FactVal": {
"entity": {
"string": "blabla"
}
}
When i read "entity" i want to know if exists a method "setEntity" in the FactVal class, i think i have to do this: the value of 'i' is "FactVal" and the value of 'j' is "entity".
if(UTIL.Classes[i].("set" + j[0].toUpperCase() + j.substring(1,j.length)))
and dont work, how can i do it?
Thanks.
You're close, you want [] and you need to look at the prototype property of the constructor function, not the constructor function itself:
if(UTIL.Classes[i].prototype["set" + j.charAt(0).toUpperCase() + j.substring(1,j.length)])
(I also replaced your j[0] with j.charAt(0), not all JavaScript engines in the wild support indexing into strings like that yet.)
Or better:
if(typeof UTIL.Classes[i].prototype["set" + j.charAt(0).toUpperCase() + j.substring(1,j.length)] === "function")
That works because you can access the property of an object either via the familiar dotted notation with a literal:
x = obj.foo;
...or via bracketed notation with a string:
x = obj["foo"];
// or
s = "foo";
x = obj[s];
// or
p1 = "f";
p2 = "o";
x = obj[p1 + p2 + p2];
Instead of
FactVal.setEntity
You have to look at the prototype, just like you did when setting the property originally:
Factval.prototype.setEntity
also, you need to use bracket notation istead of parenthesis (like you did with the [i]):
if( UTIL.Classes[i].prototype["set" + j[0].toUpperCase() + j.substring(1,j.length)] )
You need to use indexer notation:
if (typeof URIL.Classes[i]["set" + (...)] === "function")
Your question looks like this :
Turning JSON strings into objects with methods
However, that line :
if(UTIL.Classes[i].("set" + j[0].toUpperCase() + j.substring(1,j.length)))
Should be replaced with :
if(typeof UTIL.Classes[i]["set" + j[0].toUpperCase() + j.substr(1)] === "function")
NOTE : j.substr(1) is equivalent to j.substring(1,j.length)

Can I create a method in an object?

I saw this code before, but I don't know what the meaning:
var person1 = {
toLocaleString : function(){
return "Nikolaos";
},
toString : function(){
return "Nicholas";
}
}
var person2 = {
toLocaleString : function(){
return "bum";
},
toString : function(){
return "Greg";
}
}
var people = [person1, person2];
alert(people.toString());
alert(people.toLocaleString());
does the function create an object with the method of toLocaleString and toString??or...??
That code is doing three things:
Using object literal syntax to create object instances
Using anonymous function expressions to create functions and bind them to properties on the objects. (Functions are first-class objects in JavaScript, so you can keep references to them, pass the references around, etc.)
Specifically, it's overriding two standard functions that all JavaScript objects inherit from the Object prototype.
Let's break it down a bit.
1) Object literal notation:
var obj = {propName: propValue};
The { and } in this case denote an object literal. Within an object literal, you can write propName: propValue to assign propValue to the property with the name propName on the object. This is the same as:
var obj = {}; // Get an empty object
obj.propName = propValue; // Add a property to it
You can do multiple properties separated with commas. So for instance:
var obj = {
author: "Douglas Adams",
title: "The Hitchhiker's Guide to the Galaxy",
answer: 42
};
That creates an object with three properties, two with string values and one with a number value.
Note that the right-hand side are processed just like an assignment, and so can be anything that can appear on the right-hand side of an assignment statement:
var x = "bar";
var obj = {
three: 1 + 2,
fubar: "foo " + x
};
The property names can be put in quotes if you like:
var x = "bar";
var obj = {
"three": 1 + 2,
"fubar": "foo " + x
};
...which is handy for specifying properties that have the names of reserved tokens (like "if", or "return") or formerly-reserved tokens (like "class") where it would be a syntax error if they weren't in quotes.
2) Now let's look at function expressions:
var f = function() { /* your code here */ };
That's a function expression. It creates a new function and assigns a reference to it to the variable f. You can call it by calling f().
var f = function(name) {
alert("Hi " + name);
};
f("Fred"); // alerts "Hi Fred"
1 + 2) So putting it together with object literal notation:
var obj = {
foo: function(name) {
alert("Hi " + name);
}
};
obj.foo("Fred"); // alerts "Hi Fred"
(I don't like anonymous functions, I prefer my functions to have names, but that's another topic.)
3) And finally: As maerics pointed out, the specific functions that are being used in that code are toString and toLocaleString, both of which are standard functions of JavaScript objects. That means that those will override the standard version and so return the given values whenever the standard function would have been called.
The toString() and toLocaleString() methods are implemented for all JavaScript objects by the specification of the language. So arrays (such as the one stored in the "people" variable) seem to implement those methods by returning each of their elements' string or "locale string" value, respectively (at least, in the web browsers we are testing).
That is, the Array class toString and toLocaleString methods must be implemented with something like:
Array.prototype.toString = function() {
var a = [];
for (var i=0; i<this.length; i++) {
a[i] = this[i].toString(); // Note "toString".
}
return a.join(",");
}
Array.prototype.toLocaleString = function() {
var a = [];
for (var i=0; i<this.length; i++) {
a[i] = this[i].toLocaleString(); // Note "toLocaleString".
}
return a.join(",");
}

Categories