I have this code here:
var myRequest = new httpReq.myRequest(buffer,socket);
if(!myRequest.hasSucceded()){ //return error
return;
}
arr=myRequest.getCookies();
....
and i definitely have this function on my myRequest object:
function myRequest(buffer, socket) {
...
this.cookies = new Array();
...
//returns the cookie array
function getCookies() {
return this.cookies;
}
...
}
exports.myRequest = myRequest;
and i get an error saying:
TypeError: Object #<myRequest> has no method 'getCookies'
Y U NO GIVE COOKIES???
help please...
You are declaring getCookies as a local function.
To call it externally, you need to create a property getCookies on your object so you can call it.
Try this:
function myRequest(buffer, socket) {
...
this.cookies = new Array();
...
//returns the cookie array
this.getCookies = function() {
return this.cookies;
}
...
}
You also could just do myRequest.cookies instead of myRequest.getCookies()
function myRequest(buffer, socket) {
this.cookies = [];
}
myRequest.prototype.getCookies = function () {
return this.cookies;
};
First, declaring getCookies inside constructor directly causes this method to be a private method, which only lives within the constructor.
Second, usually it is considered a good practice to define the prototype getCookies outside the constructor. If it is defined in the constructor (like, this.getCookies = function () {...}), this method would need to be initialized every time when this prototype is instantiated.
Related
function DoIHavePrototype()
{
var a = 10;
}
CheckIt = new DoIHavePrototype();
DoIHavePrototype.prototype.GetFnName = function()
{
return "DoIHavePrototype"
}
alert(CheckIt.GetFnName())
In the above code,I observe that prototype is an in-built property for the function using which we can append property/method to a function.
But if I remove the prototype keyword in the above code like the following:
DoIHavePrototype.GetFnName = function()
{
return "DoIHavePrototype"
}
I don't get error in function definition but instead I get error while calling the method
alert(CheckIt.GetFnName()) as "CheckIt.GetFnName is not a function"
What does the JS interpreter assume this to be??
In order to be able to invoke some function a method on an object, there are 4 ways to introduce it to the object.
The first way is what you've done in your original code, which is to assign the function to the object prototype:
Foo.prototype.myFunc = function () { .... }
Another way is to assign it to this within the constructor.
function Foo() {
this.myFunc = function () { .... }
}
We can also assign it directly to the instance:
var foo = new Foo();
var myFunc = function () { .... }
foo.myFunc = myFunc
Finally, we can bind a function to the instance:
var foo = new Foo();
var myFunc = function () { .... }
var myFuncFoo = myFunc.bind(foo)
The last case is a bit special since we have a function that's not a property of the instance, but behaves like an instance method because it's invocation context is affixed to the instance.
The most common way of defining instance methods is assignment to the prototype. The prototype property on the constructor is what the instances inherit from, so that's where we put stuff. It's important to keep in mind that the instances inherit from the prototype property, not the constructor function. Assigning anything to a constructor property does not make it available as an instance property.
Assignment to this can sometimes be used if we want to have a method that's bound. For instance:
function Foo() {
this.boundMeth = this.meth.bind(this)
this.val = "foo"
}
Foo.prototype.meth = function () {
console.log(this.val)
}
This is useful if we want to pass instance.boundMeth() as a value to another function (e.g., event handler). In JavaScript, unlike many OO languages, methods are unbound:
// Using Foo from the previous example
function runner(fn) {
fn()
}
var obj = new Foo()
runner(obj.meth) // Logs `undefined`
runner(obj.boundMeth) // Logs `foo`
When assigning to the constructor prototype, you can assign in bulk:
Foo.prototype = {
meth1: function () { .... },
meth2: function () { .... },
}
If you use ES6, you can also use the class keyword:
class Foo {
myFunc() { .... }
}
This is the same as Foo.prototype.myFunc = function () { .... }.
If you append your function straight to the class it will generate so called static method which you can only call from you class like in Array.from.
So in your case you should call it using you class (not its instances) like so DoIHavePrototype.GetFnName();
you can read about this on MDN
This can also be done, in case if you still want to use it as instance method.
function DoIHavePrototype()
{
var a = 10;
this.GetFnName = function() {
return "DoIHavePrototype";
}
}
CheckIt = new DoIHavePrototype();
alert(CheckIt.GetFnName())
I have this code example:
function s () {
this.func = [];
this.func.addF = function (str) {
this.func.push(str);
}
}
When I create an Instance of that object:
var a = new s ();
a.func.addF ("hello");
I get an error saying: Uncaught TypeError: Cannot read property 'push' of undefined.
I can understand that this.func is undefined at that point, but what should I do to make this work. Pls help.
There is a problem with this. In javascript, this point to the binding context or what was used to invoke the function call. The value of this is determined by how a function is called.
function s () {
var self = this;
self.func = [];
self.func.addF = function (str) {
self.func.push(str);
}
}
var a = new s ();
a.func.addF("hello"); // Display 'hello'
Are you trying to add the method to the inner object (the array) or the outer object (the one constructed by s)?
If the function is intended to be added to the outer object
function s () {
this.func = [];
this.addF = function (str) {
this.func.push(str);
}
}
If the function is intended to be added to the inner (array) object
function s () {
this.func = [];
this.func.addF = function (str) {
this.push(str);
}
}
The reason has to do with how this is defined. When you call the method like this:
a.func.addF ("hello");
the variable this does not refer to a, it refers to a.func. a.func does not have a property func, but it does have the method push, so if you really intended to add the function to the array object itself, then just use this.push.
I found code similar to this in a legacy app:
var Example = function (var1, var2, var3) {
this.prop1 = var1;
this.prop2 = var2;
this.prop3 = var3
};
Example.prototype = function () {
var showAlert = function (message) {
alert(message);
}
};
var example = new Example(null, null, null);
So I tried to access the prototype method like this:
example.showAlert("hello");
Here is the jsfiddle: http://jsfiddle.net/64dkjke1/
It doesn't work . . . the showAlert method is undefined. The prototype is equal to a function that defines other functions inside . . . hopefully I'm just overlooking something simple here.
How can I access this prototype function?
Thank you.
If you have no problem changing the original code, you can do the following to have the prototype receive an object using IIFE:
Example.prototype = (function () {
return {
showAlert : function (message) {
alert(message);
}
}
})();
var example = new Example(null, null, null);
example.showAlert("hello");
Fiddle
Was it like this instead, attaching an object to the prototype? It's difficult to determine what the issue is because you say that the code you've posted is only similar to the code in the legacy app, so we can't really know for sure.
Example.prototype = {
showAlert: function (message) {
alert(message);
}
}
You can't, cause
var showAlert = function (message) {
alert(message);
}
is private.
you can do this:
function abc(){
var myPrivateVar = "Hello";
this.alert = function(){
alert(myPrivateVar);
}
}
new abc().alert();
but not this
var a = new abc();
alert(a.myPrivateVar);
You cannot access the function showAlert() (as you have already figured out) The reason for this is simple.
Example.prototype = function ()
Does not extend your prototype by a function but overrides the whole prototype (which you usually don't want to do unless you are very aware of what you're doing). In JavaScript the prototype of a class is a function itself. You have access to your prototype by calling myClass.prototype which will return your prototype object.
The prototype can be extended (like every other object in JavaScript aswell)
quick example:
Example.prototype.showAlert = function(message){ alert(message); };
now you could call:
Example.prototype.showAlert("Hi");
// or calling it from an instance of Example:
var myExample = new Example();
myExample.showAlert("Hi")
So what your fiddle does is it replaces the whole prototype with this:
function () {
var showAlert = function (message) {
alert(message);
}
};
One could argue that this new function does not serve well as a prototype, but still IS callable (to come back to your original question). You can call it like this:
Example.prototype()
But nothing will happen since the only thing happening in this function is that it will declare a 'private' function inside this prototype-scope, which never gets called.
// start of prototype function
var showAlert = function (message) {
alert(message);
}
// end of prototype function
I cannot imagine this is what your intention was, so my advice is to stick to extending prototypes (but even that only if you have to).
I'm currently learning prototyping in javascript, i wrote the below and it seems to work fine when i use it. my question was why do i need the () at the end of the prototype declaration, without that if i try to make an instance of the object I get an error.
var MyTest = function (agencyId, dataId) {
this.agencyId= agencyId;
this.dataId= dataId;
};
MyTest.prototype = function () {
var setObservables = function () {
...
},
init = function (url) {
...
};
// public members
return {
init: init
};
}();
to use it I call it like
var obj = new DetailsDivisionKO(1, 2);
obj.init(actionUrl);
this works fine, but I'm confused about the }(); at the end of the public members section, why is that needed and I can not have that and still use the above code to call it? As without that if i try to call the above code I get a error stating:
Uncaught TypeError: Object [object Object] has no method 'init'
What you have is an IIFE. Its an imidiately invoked function. You are basically creating a closure. You are exposing your init function while preserving a true private scope to your setObservables function. So every time you create a new instance of the constructor, your init function will always be in the prototype. But setObservables will not. In your example you could only access setObservables function internally (hence private scope). Usually you would do that if you only want your init function to call your private functions which in your case is setObservables. But if this is not what you want, you simply can do this:
var MyTest = function (agencyId, dataId) {
this.agencyId= agencyId;
this.dataId= dataId;
};
MyTest.prototype = {
setObservables: function () {
...
},
init: function (url) {
...
}
}
Now every time you will create a new instance of MyTest, both of your functions will be in its prototype.
var test = new MyTest(1, 2);
test.init();
test.setObservables();
I'm wondering if any of yall have any insight as to how one could execute a function by reference in javascript.
http://mootools.net/shell/yL93N/1/
Any discussion would be cool.
-Chase
looking at your mooshell, the way i'd handle it in mootools is this:
http://mootools.net/shell/yL93N/10/
var proxyFunction = new Class({
message: "hello",
Binds: ['passByReference','sayit'],
passByReference: function(func) {
// console.log(this, this[func]);
if (this[func] && $type(this[func]) === "function")
this[func]();
},
sayit: function() {
alert(this.message);
},
killit: function() {
document.write('we\'re dead');
}
});
$('tryit').addEvent('change',function(e){
new proxyFunction().passByReference(this.get('value'));
});
// or have a permanent proxy instance if you call methods of the class often and need it to change things.
var proxy = new proxyFunction();
$('tryit').addEvent('change',function(e){
proxy.passByReference(this.get('value'));
});
the advantage of doing so is that all your proxied functions are behind a common object, don't pollute your window namespace as global variables and can share data that relates to the event.
Not exactly sure what you mean, but you can do this:
var func = window.alert;
var args = ["hello world"]
func.apply(window, args)
Globally-defined functions (and variables) are visible as members of the global window object.
Members of an object can be fetched by name using the square bracket notation: o['k'] is the same as o.k. So, for your example:
var function_name= $(this).val();
window[function_name]();
Like this?
function blah() {
...do stuff
}
myref = blah
myref()
The best way is to do:
func.call();
Function variables in JavaScript already are references. If you have a function:
var explode = function() { alert('boom!'); };
You can pass explode around as an argument, and it's only passing a handle to that function, not the entire function body.
For proof of this, try:
explode.id = 5;
var detonate = explode;
alert(detonate.id); // => 5
explode.id = 6;
alert(detonate.id); // => 6
functions are first class objects in Java Script. Effectively this means that you can treat it very much as if it were a variable, and pass it anywhere that you would expect a variable.
e.g.
var myFn = function() { alert('inside anonymous fn'); }
function callMyFn(paramFn)
{
paramFn();
}
callMyFn(myFn); //inside anonymous fn
function MyFnHolders(argFn)
{
this.argFn = argFn;
this.fieldFn = function() {
alert('inside fn field');
}
}
var myFnHolders = new MyFnHolders(myFn);
myFnHolders.argFn(); //'inside anonymous fn'
myFnHolders.fieldFn(); //'inside fn field'
//etc
so passing a function by ref can be done simply by assigning it to a variable and passing it around.
Here's one with a closure for your arguments...
function Runner(func, args) {
return function() { return func.apply(window, args); };
}
var ref = new Runner(window.alert, ["hello world"]);
ref();