In the following code example :
var oldConstructor = Error.constructor;
Error.constructor = function() {
console.log('Constructor');
oldConstructor.apply(null, arguments);
};
var a = new Error('ok');
Why isn't 'Constructor' printed ?
How can I run a function every time a native Error object's constructor is called ?
The goal I'm trying to achieve is that rather than bubbling Errors up the callback chain of the different modules used in my code base (mongoose, express.js, ...etc), I just want every error to emit an event or call a method (maybe with an Observer pattern).
I'm trying to solve the problem this way rather than modifying every line of code creating a new Error object.
Thanks in advance !
Error.constructor is a reference to the Function function, because Error is a function and functions are constructed by Function.
You could have done:
var oldError = Error;
Error = function( arg ) {
console.log('Constructor');
return new oldError( arg );
};
But this is not guaranteed to work at all as modules could have stored a local reference to the Error constructor if they run before your code.
You could instead use the uncaughtexception event
Related
I have a method in my vue js element:
_deleteDesign : function(dsn)
{
//_deleteDesign
var url = '{{ url('/fapi/designsTmp/') }}/'+dsn.design_id;
axios.delete(url)
.then(function(){
this.$delete(this.creations, this.creations.indexOf(function(el){
return el.design_id = dsn.design_id;
}));
})
.catch(function(e){
alert('error deleting design');
})
debugger;
}
In this method I am using the indexOf function of Javascript, but vuejs reports me this error in the Chrome debugger:
this.creations.indexOf is not a function
What's the problem?
The this context has changed in the promise then handler because of new function declaration. One way to fix, would be to use ES6 arrow function which keeps the existing this binding for code within the function:
.then(() => {
this.$delete(this.creations, this.creations.indexOf(function(el){
return el.design_id = dsn.design_id;
}));
})
"indexOf" method can only be executed on variables that are type "string" or "array" (which is actually type "object").
So in your particular case "this.creations" must be either array or string. The issue is that you somehow ended up with the case when "this.creations" is not one of those types.
One possible solution is to add
console.log(typeof this.creations)
and monitor the type of this variable.
Also as previous answer mentioned the issue is that "this" changed context. One solution for this is to make copy of this object:
const self = this;
in the beggining of _deleteDesign function and to use "self" object instead of "this". Generally avoid using "this" object as much as possible.
I've a crazy problem. I'm instantiating an object from a class. Then I want to pass a function from this object to the setInterval function. The whole code block is executed with a keyDown event.
Here's the code:
function doKeyDown(e){
var instance = new Class(e.keyCode);
setInterval(instance.functionToBeExecuded(), 200);
}
The strange thing is that it's getting executed once and then starts to loop an error which states (firebug):
27
SyntaxError: missing ] after element list
[object HTMLAudioElement]
For the sake of completeness:
Class.prototype.functionToBeExecuded = function(){
var node = document.createElement("audio");
//the key is stored in the object (from the Class's constructor)
node.setAttribute("key", this.variable);
}
Does anyone see some fails?
Thanks in advance! =)
P.S.: This is not a duplicate cause I'm not facing the function, function() error. If I'm executing it with (instance.functionToBeExecuded, 200) it happens just nothing.
What I've found out so far is that the problem must be in the scope somehow. If I do it like this:
function doKeyDown(e){
var instance = new Class(e.keyCode);
setInterval(instance.functionToBeExecuded, 200);
}
Class.prototype.functionToBeExecuded = function(){
console.log(this);
var node = document.createElement("audio");
//the key is stored in the object (from the Class's constructor)
node.setAttribute("key", this.variable);
}
I'm getting a looping console output with "window". So the function is executed in the window's scope. But why? And how to work around?
Console output:
Window index.html
The workaround would be: wrap it using another function instead of calling method directly
function doKeyDown(e){
var instance = new Class(e.keyCode);
setInterval(function(){
instance.functionToBeExecuded()
}, 200);
}
This would give output many of these:
Class {functionToBeExecuded: function}
I am having problems getting a reference to a javascript object implemented with the
prototype pattern within a callback. The callback is from a 3rd party component
I utilize within my object. The 3rd party object connects to a message bus.
The following pseudo code shows how I started (The real code for this is working)
var mb = require('MsgBus')
TestClass = function() {
this.messagebus = new mb.MsgBus();
this.messagebus.connect(function(err) {
if(err)
console.log("Error connecting");
else
console.log("Connected");
});
}
But then I wanted to have it automatically retry connecting if the callback reports
an error. I cannot just put another line if the if(err) block that
says "this.messagebus.connection" because I would have to add another anonymous
method for that connect callback and it would just go on and on. So, I want to
split out the callback logic to a named function like this
var mb = require('MsgBus')
TestClass = function() {
this.messagebus = new mb.MsgBus();
this.messagebus.connect(msgBusConnectCallback);
}
function msgBusConnectCallback(err) {
if(err)
this???.messagebus.connect(msgBusConnectCallback);
else
console.log("Connected");
});
}
The callback function gets called, but I cannot figure out how to get a reference
to the object to call connect again. I've also tried to make the callback a
prototype function of the object, still no reference. I cannot create a variable
in the global scope to maintain "this" because the user of this class may
create multiple instances of the class. I am fairly new to JavaScript so I don't
know if I'm just missing something or if I need to take a different approach
altogether. I would appreciate any help and/or direction.
this.messagebus.connect.apply(this, [msgBusConnectCallback]);
I finally figured out the answer, the correct syntax is
this.messagebus.connect(msgBusConnectCallback.bind(this));
I found in requirejs-text plugin weird code. So load method accepts onLoad callable which is invoked for a few times as onLoad(), but later there is error handler which checks for an error method.
if (onLoad.error) {
onLoad.error(err);
}
Am i missing something or it's obvious code issue?
You cannot use a normal object as a callable entity, but a function is a type of object, so you can add properties to a function.
var onLoad = function(){
};
onLoad.error = function(){
};
I'm new to JavaScript programming.I wrote an IIFE that will help me improve my understand. My intention is to define a $ function that when called will call itself as a constructor. When the code is run, it generates an error 'Too much recursion'. I don't know what the problem is.
(function() {
//check the global host object
var root = this;
var inside = "inside";
var $ = function () {
return new $(); //this line generates an error 'Too much recursion.'
}
$.check = function(obj) {
console.log(inside);
}
//add the $ to global object
root.$ = $;
}).call(this);
var ins = $();
console.log(ins);
var $ = function () {
return new $(); //this line generates an error 'Too much recursion.'
}
This function is repeatedly calling itself, which is why you see the Too much recursion. error. You aren't distinguishing between a regular function call and a new call.
My intention is to define a $ function that when called will call itself as a constructor.
The simplest way is to explicitly check this:
var $ = function $() {
if(!(this instanceof $)) return new $();
// ... from this point on, behave as if called via new
}
this line generates an error 'Too much recursion.'
Right. You have a function assigned to the $ symbol which calls the function assigned to the $ symbol. So each call (whether direct or via new) will run the code in that function, which makes another call to it, and so on until you exceed the engine's willingness to recurse. To avoid that, have $ do something else.
It's because you have created an infinite loop. By using parenthesis when returning your new var instance you are recursively calling that function with no parameters. I'm not sure what you are trying to accomplish, but you might want to have $ create a new object "{}" instead and then you can extend methods off of that reference. Look into singleton patterns, that will allow you to create a new instance of something.
*edit, and just to be clear your problem doesn't have anything to do with it being an IIFE, you would encounter this same error anywhere you tried to call a new function on itself in this manner.