If I have a function like this:
function foo(_this) {
console.log(_this);
}
function bar() {}
bar.prototype.func = function() {
foo(this);
}
var test = new bar();
test.func();
then the test instance of bar gets logged.
However, for this to work I have to pass the this in the bar.prototype.func function. I was wondering whether it is possible to obtain the same this value without passing this.
I tried using arguments.callee.caller, but this returns the prototype function itself and not the this value inside the prototype function.
Is it possible to log the test instance of bar by only calling foo() in the prototype function?
If the question is 'without passing this (by any means)' then answer is no
value can be passed by alternative methods though. For example using global var (within Bar class) or session or cookies.
function bar() {
var myThis;
function foo() {
console.log(myThis);
}
bar.prototype.func = function() {
myThis = this;
foo();
}
}
var test = new bar();
test.func();
I think calling foo within the context of bar should work:
function foo() {
console.log(this.testVal);
}
function bar() { this.testVal = 'From bar with love'; }
bar.prototype.func = function() {
foo.call(this);
}
var test = new bar();
test.func(); //=> 'From bar with love'
You can do this without changing the external function, but you must change the way you call it.
You can't get the context of the caller, but you can set the this property on a function you call with the method apply or call. See this reference for an explanation on this.
function foo()
{
console.log( this );
}
function bar()
{
bar.prototype.func = function func()
{
foo.apply( this );
};
}
var test = new bar();
test.func();
Usually if this is used, it's in an object oriented context. Trying to call a method of an object with another this might indicate poor design. Explain a bit more what you are trying to achieve for more applicable design patterns.
For an example of a javascript OOP paradigm, check my answer here.
What about this?
"use strict";
var o = {
foo : function() {
console.log(this);
}
}
function bar() {}
bar.prototype = o;
bar.prototype.constructor = bar;
bar.prototype.func = function() {
this.foo();
}
var test = new bar();
test.func();
Or this:
"use strict";
Function.prototype.extender = function( o ){
if(typeof o == 'object'){
this.prototype = o;
}else if ( typeof o == 'function' ) {
this.prototype = Object.create(o.prototype);
}else{
throw Error('Error while extending '+this.name);
}
this.prototype.constructor = this;
}
var o = {
foo : function() {
console.log(this);
}
}
function bar() {}
bar.extender(o);
bar.prototype.func = function() {
this.foo();
}
var test = new bar();
test.func();
Related
I have a function foo:
function foo() {
return 'foo';
}
While foo got executed is there a way to know if foo was called inside object declaration ? I want to distinguish these two cases:
var bar = {
prop1: foo()
}
var var1 = foo();
Here's one approach demonstrating the suggestions in the comments and assuming you'd rather call bar.prop1 instead of bar.prop1().
function foo (ctx) {
console.log(ctx == window)
return 'foo'
}
class Bar {
get prop1() {
return foo(this)
}
}
var var1 = foo(this);
var bar = new Bar();
bar.prop1;
I have a javascript object from which I created from a constructor.
var obj = new Obj();
It has several functions but I wish to also use it as follows;
obj();
Obj is defined as:
function obj() {
this.blah = function () {
};
}
How can I do this?
It would be easier to have a function you call which returns an arbitrary function that is treated as both an object and a function. Each one would be unique, and you would not need to use new.
function Obj() {
var ret = function(){
console.log('Hello');
};
ret.blah = function () {
console.log('World');
};
return ret;
}
var obj = Obj();
obj();//Hello
obj.blah();//World
You can create properties on function objects. For instance, if you have the function
function foo() {
return "bar";
}
You can set a property on foo.
foo.baz = 42;
So now you can call foo and get the result "bar", and you can access its baz property.
I think you are looking for 'closure' here.
Try:
function MyObject(/* constructor params */) {
//assign properties to 'this'
return function() {
return this; //<== placeholder implementation
}.bind(this);
}
var obj1 = new MyObject();
Now if you do console.log(obj1) you will see function() { [...] } and you will be able to do obj1() to execute your function.
As a bonus in the code above, I also added this binding in the 'closure' as you will need it in most cases that you are doing anything interesting.
How can I access a method from a parent class that was overridden in the child class?
In My example below I want to call the bar.my_name() method inside the overriding
method in foo.my_name()
function bar() {
this.my_name = function() {
alert("I Am Bar");
}
}
function foo() {
this.my_name = function() {
alert("I Am Foo");
//access parent.my_name()
}
}
foo.prototype = Object.create(bar.prototype);
foo.prototype.constructor = foo;
var test = new foo();
test.my_name();
You could do this:
(new bar()).my_name.call(this);
I think you're a little confused about how prototypes work though, as they're not really helping you here.
This might be slightly better:
var bar = {
my_name: function () {
console.log('bar name');
}
};
var foo = Object.create(bar);
foo.my_name = function () {
console.log('foo name');
bar.my_name.call(this);
};
Or if you want to use constructors, something like this:
function Bar () {}
Bar.prototype.my_name = function () {
console.log('bar name');
};
var foo = Object.create(Bar.prototype);
foo.my_name = function () {
console.log('foo name');
bar.my_name.call(this);
};
But I'm not really sure what you're trying to do or why, so with more context it will be easier to give you better advice.
One of possible solutions is to move the method to the base class prototype.
function bar() {
}
bar.prototype.my_name = function() {
alert("I am bar");
}
function foo() {
}
foo.prototype = Object.create(bar.prototype);
foo.prototype.my_name = function() {
alert("I Am Foo");
bar.prototype.my_name.call(this);
}
foo.prototype.constructor = foo;
var test = new foo();
test.my_name();
This little gem is giving me a bit of a headache. Let's say I create an object that returns a function, like this:
function Bar(prop) {
this.prop = prop;
var that = this;
return function() {
this.prop = that.prop;
}
}
var bar = new Bar();
console.log(bar instanceof Bar);
Bar() returns a function, as you can see. Now, Bar() instanceof Bar returns false, which isn't what I want. How do I check to see if a new Bar() is an instance of Bar? Is this even possible?
Returning any object from a constructor will use that object instead of returning an instance automatically generated by the constructor. It's a bit abstract, so here's an example to show my point:
function Foo() {}
function Bar() {
return new Foo();
}
f = new Foo();
console.log(f instanceof Foo); //true
b = new Bar();
console.log(b instanceof Bar); //false
console.log(b instanceof Foo); //true
Everything in JavaScript is an object, including functions, so the fact that your foo.bar function returns a function means that when you call new foo.bar() you're going to receive the function returned by foo.bar instead of a new foo.bar instance.
While I'm not 100% certain of what you're trying to do exactly, you can check whether a function is being called as an object initializer or as a function simply by using instanceof on the context. This pattern is often used for forcing object initialization:
function Foo(...arguments...) {
if (!(this instanceof Foo)) {
return new Foo(...arguments...);
}
//do stuff
}
This allows Foo to be called as a function and still return a new Foo instance:
a = new Foo(); //a instanceof Foo
b = Foo(); //b instanceof Foo
Not entirely sure why you'd want to do what you are doing but I see what the issue is.
In the scope of 'test', this.bar is the function bar(prop) rather than the function returned as a result of executing this function, if that makes sense. However, new this.bar('hi') will be first executing bar('hi'), which returns an anonymous function that then acts as the constructor.
In other words, you are comparing an instance created from the anonymous function with a different function so instanceof is correctly returning false.
The following logs 'true' but may not be what you are looking for:
function foo() {
this.test = function() {
var cls = this.bar('hi');
console.log(new cls() instanceof cls);
};
this.bar = function bar(prop) {
this.prop = prop;
var that = this;
return function() {
this.prop = that.prop;
}
}
}
var test = new foo();
test.test();
I'm fairly certain this isn't possible, but wanted to see if anyone had some ingenious ideas as to how to make it possible.
I want the following code to work:
var x = new foo();
x.a.getThis() === x; // true
In other words, I want x.a.getThis to have a reference to this being x in this case. Make sense?
In order to get this to work one level deep is simple:
function foo(){}
foo.prototype.getThis = function(){ return this; }
var x = new foo();
x.getThis() === x; // true
One thing, I want this to work as a prototype, no "cheating" by manually binding to this:
function foo(){
this.a = {
getThis : (function(){ return this; }).bind(this)
};
}
Although the above is a perfect functional example of what I'm trying to achieve, I just don't want all the extra functions for each instance :)
FYI, the actual use case here is that I'm creating classes to represent Cassandra objects in node and I want to be able to reference a super-column --> column-family --> column via foo.a.b and keep a reference to foo in the deep function.
You can't do this without a forced bind of some kind. You say you don't want to "cheat" but this breaks the standard rules about what this is, so you have to cheat. But JS lets you cheat, so it's all good.
BTW, for what it's worth coffee script makes this so trivial.
foo = ->
#a = getThis: => this
The fat arrow => preserves the context of this for from the scope it was called in. This allows you to easily forward the context to another level.
That code gets compiled to this JS:
var foo;
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
foo = function() {
return this.a = {
getThis: __bind(function() {
return this;
}, this)
};
};
Which basically just does what you say you do not want to do.
Or if the value doesn't have to this specifically, you can set the "owner" in the child object.
var A = function(owner) {
this.owner = owner;
};
A.prototype.getThis = function() {
return this.owner;
};
var Foo = function() {
this.a = new A(this);
};
var foo = new Foo();
if (foo.a.getThis() === foo) {
alert('Happy dance');
} else {
window.location = 'https://commons.lbl.gov/download/attachments/73468687/sadpanda.png';
}
http://jsfiddle.net/4GQPa/
And the coffee script version of that because I am a passionate and unreasonable zealot for it:
class A
constructor: (#owner) ->
getThis: -> #owner
class Foo
constructor: -> #a = new A(this)
foo = new Foo()
if foo.a.getThis() is foo
alert 'Happy Dance'
else
window.location = 'https://commons.lbl.gov/download/attachments/73468687/sadpanda.png'
Impossible to do reliably without binding the value at the start since the value of a function's this is set by the call. You can't know beforehand how it will be called, or which functions need a special or restricted call to "preserve" the this -> this relationship.
The function or caller's this may be any object, there may not be a this -> this at all. Consider:
var x = {
a : {
b: function() {return this;}
}
}
When you call x.a.b(), then b's this is a. But if you do:
var c = x.a.b;
c(); // *this* is the global object
or
x.a.b.call(someOtherObject);
What is the value of this -> this in these cases?
Answering my own question because someone else may find it useful. Not sure if I'll end up going with this or Squeegy's solution. The functions are only ever defined once and then the containing object is cloned and has parent = this injected into it:
function foo(){
var self = this, nest = this.__nestedObjects__ || [];
nest.forEach(function(prop){
self[prop] = extend({ parent : self }, self[prop]);
});
}
// bound like this so that they're immutable
Object.defineProperties(foo.prototype, {
bar : {
enumerable : true,
value : {
foobar : function(){
return this.parent;
},
foo : function(){},
bar : function(){}
}
},
__nestedObjects__ : { value : ['bar'] }
});
var fooInst = new foo();
console.log(fooInst.bar.foobar() == fooInst);
or based on Squeegy's solution:
function foo(){
for(var cls in this.__inherit__){
if(!this.__inherit__.hasOwnProperty(cls)){ continue; }
this[cls] = new (this.__inherit__[cls])(this);
}
}
var clsA;
// bound like this so that they're immutable
Object.defineProperties(foo.prototype, {
__inherit__ : { value : {
bar : clsA = function(parent){
Object.defineProperty(this, '__parent__', { value : parent });
}
}
}
});
clsA.prototype = {
foobar : function(){
return this.__parent__;
}
};
var fooInst = new foo();
console.log(fooInst.bar.foobar() == fooInst);