How to fix 'Not a constructor function' error in javascirpt - javascript-objects

I'm trying to understand how object prototypes work and hence tried out a piece of code from 'Javascript: The Good Parts' book and got an error.
I modified the code just for fun and got the error. It works and shows an output if the original code is ran.
This is the original code and it gave no errors.
let stooge = {
'first-name': 'John',
'last-name' : 'Peter'
};
if(typeof Object.create !== 'function') {
Object.create = (o) => {
let F = () => {};
F.prototype = o;
return new F();
};
}
let theOtherStooge = Object.create(stooge);
console.log(theOtherStooge['first-name'], theOtherStooge['last-name']);
I removed the if condition and got an error saying F isn't a constructor function. Could someone explain me why this is happening? Please excuse me, I'm a beginner to programming.
Modified code:
let stooge = {
'first-name': 'John',
'last-name' : 'Peter'
};
Object.create = (o) => {
let F = () => {};
F.prototype = o;
return new F();
};
let theOtherStooge = Object.create(stooge);
console.log(theOtherStooge['first-name'], theOtherStooge['last-name']);

At least in Chrome Object.create is already defined as a function, so none of the code in the if statement of the first example is being run. Without the if statement, the code throwing the exception is run. The reason for the error is that the lambda function assigned to F is not considered a constructor. Based on this answer, the problem is that the this object is assigned to the scope surrounding a lambda function when it is created, while this is assigned to the object calling the function when using a regular function. You can change the code to use a regular function instead:
let stooge = {
'first-name': 'John',
'last-name': 'Peter'
};
Object.create = (o) => {
let F = function() {};
F.prototype = o;
return new F();
};
let theOtherStooge = Object.create(stooge);
console.log(theOtherStooge['first-name'], theOtherStooge['last-name']);

Related

Can anyone explain why my state is getting updated even when i dont set it manually

So I just spent an hour debugging this code and finally got it to work, but I would want to know why this happened in the first place. I have a function that takes a value from my state, operates on it and saves the output in another variable in the state. This is the fuction:
getFolderNames = async () => {
const promises = this.state.rows.map(async item => {
if (item[".tag"] == "folder" && item.name.length > 20) {
item.name = await getFolderName(item.name);
return item;
} else return item;
});
const result = await Promise.all(promises);
this.setState({
rowsToDisplay: result
});
};
when i run this function, it was updating both the rows and rowsToDisplay to the result variable when i was only calling setState on only one of them.
Changing the function as below solves the issue but I would like to know why.
getFolderNames = async () => {
const promises = this.state.rows.map(async item => {
if (item[".tag"] == "folder" && item.name.length > 20) {
let item2 = {
...item
};
item2.name = await getFolderName(item.name);
return item2;
} else return item;
});
const result = await Promise.all(promises);
this.setState({
rowsToDisplay: result
});
};
It's because of how JavaScript handles variables. When you set a variable to an array or object, it doesn't make a new object but rather just references the original array/object.
As such, if you set a variable to equal some object, and then set a property of that variable, the original object will also be updated. Check this snippet for an example.
var foo = {changed: false};
var bar = foo;
bar.changed = true;
console.log("foo", foo.changed)
console.log("bar", bar.changed)
You can read more about the subject here: https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0
I hope this helps you in the future, since I know I also spent many hours banging my head against exactly the sort of cases you described in your original question.

JavaScript array default assignment syntax confusion

If I create a function constructor in JavaScript like so:
function Emitter() {
this.events={}
}
and then I add a method to its prototype like so:
Emitter.prototype.on = function(type,listener) {
this.event[type] = this.events[type] | [];
this.event[type].push(listener);
}
When I call the method 'on' an instance of Emitter twice, why does it not just overwrite the original property called greet and assign it the second function? I guess I do not understand the stricture of what is happening in:
this.event[type] = this.events[type] | [];
var emtr = new Emitter();
emtr.on('greet',function(){
console.log('Hello once');
});
emtr.on('greet', function(){
console.log('Hello twice');
});
You should be using || for OR instead of |, this is invalid:
this.event[type] = this.events[type] | [];
Also, you are calling event instead of events. You should have:
this.events[type] = this.events[type] || [];
This way if this.events[type] is not undefined it will stay as is. However if it is undefined is will be assigned as an empty array: []
The code below will successfully add the two functions to emtr.events['greet'] (an array of functions):
function Emitter() {
this.events = {}
}
Emitter.prototype.on = function(type, listener) {
this.events[type] = this.events[type] || [];
this.events[type].push(listener);
}
var emtr = new Emitter();
emtr.on('greet', function() {
console.log('Hello once');
});
emtr.on('greet', function(){
console.log('Hello twice');
});
console.log(emtr.events['greet'])
So you can call them like so:
emtr.events['greet'][0]();
And
emtr.events['greet'][1]()
If instead, you would like to replace the listener then you shouldn't be using an array. Pointing to a function instead of an array of functions will suffice:
function Emitter() {
this.events = {}
}
Emitter.prototype.on = function(type, listener) {
this.events[type] = listener;
}
var emtr = new Emitter();
emtr.on('greet', function() {
console.log('Hello once');
});
emtr.on('greet', function(){
console.log('Hello twice');
});
emtr.events['greet'](); // notice how the first listener was replaced by the new one
This way you can call your listener with emtr.events['greet']().
While #Ivan is completely correct, he missed your main question of “why?”
The answer is that the logical OR operator in JS also functions as a null coalescing operator when used as part of an assignment statement.
Essentially, in the case
let x = y || “default”;
The right hand side will evaluate to the first “truthy” value and return that. In JS most things evaluate true in a logical operation except values like false, 0, null, and a few others not relevant to this question.
So in your syntax (as corrected by Ivan), you’re telling JS to assign to the events[type] property the first thing that’s true. Either itself (which will evaluate true if it’s not null, unassigned, 0, etc) or else an empty array.
The first time you add an event, it’ll be unassigned and therefore get an empty array added. Subsequently, arrays eval as true, so you’ll just keep re-assigning the property to itself which has no effect.
Make sense?
function Emitter() {
this.events = []
}
Emitter.prototype.on = function (type, listener) {
this.events[type] = this.events[type]||[]
this.events[type].push(listener);
}
Emitter.prototype.emit = function(type){
var listener = this.events[type].pop()
if(this.events[type].length>=0)
listener()
else
console.log('Nothing to emit')
}
var emtr = new Emitter();
emtr.on('greet',function(){
console.log('Hello once');
});
emtr.emit('greet')

Functions in React: my function isn't working, because of 'read-only' error. Why?

I'm trying to write a function into a React component, but I am stuck with this error:
Uncaught Error: Module build failed: SyntaxError: "productMap" is read-only
Why is this happening? And how can I fix this, so I can use productMap?
Here is my function:
printReceipt() {
var products = this.props.updateBasket.products;
//create a map of products
const productMap = {};
for(let product of products) {
if(!productMap[product.id]) {
productMap[product.id] = 1;
} else {
productMap = productMap + 1;
}
}
console.log(productMap);
}
This is happening because poductMap is of type const and const cannot change through reassignment
Change it to a let or var instead
printReceipt() {
var products = this.props.updateBasket.products;
//create a map of products
let productMap = {};
for(let product of products) {
if(!productMap[product.id]) {
productMap[product.id] = 1;
} else {
productMap = productMap + 1;
}
}
console.log(productMap);
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
Use let productMap={}; instead of const.
The const declaration creates a read-only reference to a value.
Reference
use ()=> FunctionName() instead of FunctionName()
When we call the function FunctionName(), it is just executed, but when we write () => FunctionName(), then it is only called when that particular operation is performed for example onPress.
FunctionName() sometimes doesn't work, and is only read-only, using () => FUnctionName, is a good way.

AsyncStorage.getItem returns undefined : React Native

Codeflow is-
I am checking if an entry called listobject exists in the AsyncStorage.
If it doesn't exist, then, I create an object, add few attributes and set the store. I get the store to obj as I have to compare in the next if condition.
If the listobject entry already exists(2nd time), then, it directly comes to the 2nd block, and compares. (The reason I get values to obj in 1st step is because I can have a common obj.data.isdirty condition.
Here is my code-
AsyncStorage.getItem('listobject').then((obj) => {
if(obj == undefined)
{
var obj1 ={};
obj1.data ={};
obj1.data.isdirty = true;
console.log("obj1 = "+ JSON.stringify(obj1));
AsyncStorage.setItem('listobject',obj1);
obj = AsyncStorage.getItem('listobject');
console.log("obj = "+ JSON.stringify(obj));
}
if(obj.data.isdirty)
{
obj.data.isdirty = false;
AsyncStorage.setItem('listobject',JSON.stringify(obj));
return AsyncStorage.getItem('listobject');
}
}).done();
I have 2 questions which are the outcome of the same issue-
Logs. I am setting obj1 and getting the same value for obj (so that I can compare the next if condition). Why am I not able to get the same value that I have set?
12-03 00:27:56.281 32598-487/com.abc D/ReactNativeJS: 'obj1 = {"data":{"isdirty":true}}'
12-03 00:27:56.286 32598-487/com.abc D/ReactNativeJS: 'obj = {"_37":0,"_12":null,"_59":[]}'
This is the end result of the above logs. I am getting that list.data.isdirty is undefined. I guess that because the JSON format I am accessing does not exist in obj i.e., obj.data.isdirty doesn't exist. So, how do I overcome this?
undefined is not an object (evaluating 'list.data.isdirty');
Please tell me what am I doing wrong?
I actually copied the object from one to another. It worked.
AsyncStorage.getItem('listobject').then((obj) => {
if(obj == undefined)
{
var obj1 ={};
obj1.data ={};
obj1.data.isdirty = true;
console.log("obj1 = "+ JSON.stringify(obj1));
AsyncStorage.setItem('listobject',obj1);
obj = obj1; //THIS IS WHAT I DID!
console.log("obj = "+ JSON.stringify(obj));
}
if(obj.data.isdirty)
{
obj.data.isdirty = false;
AsyncStorage.setItem('listobject',JSON.stringify(obj));
return AsyncStorage.getItem('listobject');
}
}).done();
I'm not quite following the entire question I do however see an issue with the use AsyncStorage. Going by the name, Async implies that the operations are asynchronous. So when you do getItem(key), you should either pass in a callback or use the Promise object it returns as you are doing in the first line of code.
obj = AsyncStorage.getItem('listobject');
console.log("obj = "+ JSON.stringify(obj));
obj is going to be the Promise in this case.
Then if you check on obj for the presence of a data and isDirty child property, they will not exist on the Promise.
Sometimes while doing console.log(AsyncStorage.getItem('Soomekey')) you will be getting undefined as you can't directly pull values from the AsyncStorage as returns a promise so what you should be writing is
const SomeFunction = async () => {
try {
const value = await AsyncStorage.getItem('somekey');
console.log(value);
} catch (err) {
console.log(err);
}
}

How to extend returned objects in the list returned by $asArray?

I'm having trouble decorate the objects in my list returned by $asArray in angularfire with a new method (not decorating the array itself).
The angularfire documentation seems to suggest that the right way to do this is to override the $$added method in the factory for $FirebaseArray, returning a new object that either encapsulates or extends the snapshot that gets passed in to that method. From the documentation:
// an object to return in our JokeFactory
app.factory("Joke", function($firebaseUtils) {
function Joke(snapshot) {
this.$id = snapshot.name();
this.update(snapshot);
}
Joke.prototype = {
update: function(snapshot) {
// apply changes to this.data instead of directly on `this`
this.data = snapshot.val();
},
makeJoke: function() {
alert("Why did the " + this.animal + " cross the " + this.obstacle + "?");
},
toJSON: function() {
// since we didn't store our data directly on `this`, we need to return
// it in parsed format. We can use the util function to remove $ variables
// and get it ready to ship
return $firebaseUtils.toJSON(this.data);
}
};
return Joke;
});
app.factory("JokeFactory", function($FirebaseArray, Joke) {
return $FirebaseArray.$extendFactory({
// change the added behavior to return Joke objects
$$added: function(snap) {
return new Joke(snap);
},
// override the update behavior to call Joke.update()
$$updated: function(snap) {
this.$getRecord(snap.name()).update(snap);
}
});
});
However, when I do this in my code, nothing ever gets added to the array, although I can see from outputting to the console that it is getting called.
var printMessageObjConstructor = function(snap) {
this.$id = snap.name();
this.snapshot = snap;
this.$update = function(snap) {
this.snapshot = snap;
};
this.printMessage = function() {
return this.author + "'s question is: " + this.body;
};
};
var ref = new Firebase("https://danculley-test.firebaseio.com/questions");
//What Am I Doing Wrong Here?
var arrayFactory = $FirebaseArray.$extendFactory({
$$added: function(snap, prevChild) {
var x = new printMessageObjConstructor(snap);
console.log("I am being called from FirebaseDecoratedCtlOverloadAddedinNewObj.");
return x;
},
$createObject: function(snap) {
return new printMessageObjConstructor(snap);
},
$$updated: function(snap) {
var i = this.$indexFor(snap.name());
var q = this.$list[i];
q.$update(snap);
}
});
var sync = $firebase(ref, {arrayFactory:arrayFactory});
var list = sync.$asArray();
list.$loaded(function(list) {
$scope.questions = list;
});
I've set up a new plunk stripped down to show the issue with a couple other use cases that I've tried. (The actual method I'm adding is more complex and isn't related to the view, but I wanted to do something simple to reproduce the issue.)
I think the issue is that I don't quite understand what exactly $$added is supposed to return, or what additional behavior beside returning the value to be stored $$added is supposed to have. There also doesn't really seem to be an $$added on the prototype or on $FirebaseArray to call as a super to get the default behavior. Can someone point me in the right direction?
UPDATE
For the benefit of others, after reviewing the like that Kato posted, I was able to solve the issue by adding the following, almost all copied directly from the source except for the commented line below.
$$added: function(snap, prevChild) {
var i = this.$indexFor(snap.name());
if( i === -1 ) {
var rec = snap.val();
if( !angular.isObject(rec) ) {
rec = { $value: rec };
}
rec.$id = snap.name();
rec.$priority = snap.getPriority();
$firebaseUtils.applyDefaults(rec, this.$$defaults);
//This is the line that I added to what I copied from the source
angular.extend(rec, printMessageObj);
this._process('child_added', rec, prevChild);
}
}
For the benefit of others, after reviewing the link that Kato posted, I was able to solve the issue by adding the following, almost all copied directly from the source except for the commented line below.
$$added: function(snap, prevChild) {
var i = this.$indexFor(snap.name());
if( i === -1 ) {
var rec = snap.val();
if( !angular.isObject(rec) ) {
rec = { $value: rec };
}
rec.$id = snap.name();
rec.$priority = snap.getPriority();
$firebaseUtils.applyDefaults(rec, this.$$defaults);
//This is the line that I added to what I copied from the source
angular.extend(rec, printMessageObj);
this._process('child_added', rec, prevChild);
}
}

Resources