How to borrow a method from a different object in JavaScript? - javascript

I am new to Inheritance, and I was just trying to inherit a method from a different object in JavaScript, but when I run the code it gives an undefined function error.
Can anyone please help me how do I inherit the method from a different object?
Below is the JS Snippet:
var palestrina = {
work: "MTS",
describe: function() {
return this.work;
}
};
var pale = {
work: "STMS"
describe: palestrina.describe.bind(this)
};
console.log(palestrina.describe());
console.log(pale.describe());
JSfiddle for the same

The value of this is determined by how the current function was called.
Since you aren't in a function, it will be window.
There is no way to get a reference to pale that you can pass to bind until after you've created the object.
However, you don't need to. Since the value of this depends on how the function is called (as opposed to how it was constructed), you can just copy the reference to the function:
var pale = {
work: "STMS",
describe: palestrina.describe
};

Related

Unable to access another object in javascript

I have uploaded a sample code where there are two objects defined using the modular pattern.
var obj1 = {
cachdom: function() {
// querying a dom element
this.$interactiveReport = $('#BugPreventiveIR_data_panel');
}
};
var obj2 = {
$IR: obj1.$interactiveReport,
logging: function() {
// This returns undefined
console.log(this.$IR);
}
};
// Invoking the Objects only after document is ready.
$(document).ready(function() {
console.clear();
interactiveReportRegion.init();
displayOfBugList.logging();
});
However, when I check in console the obj2.logging returns undefined for this.$IR. However, if I were to access obj1.$interactiveReport through console I can view the object values. Similairly, if I were to define the second object in the console again, it obtains the correct value for obj2.$IR.
Any reason I am unable to access the first object's properties in the second object?
My entire code can be found here
https://gist.github.com/alaghu/6225e50b35ecfdaf2ee8f752f596f49b
The logging function needs to know what "this" means since it's not a constructed object.. this should do it.
displayOfBugList.logging.apply(displayOfBugList);
defining a function changes the scope for "this". Consider using lamda functions to fix this. There is also the ability to bind what "this" is but I shy away from that method

Getting the Parent Function that Created an Instance

So this is a somewhat weird problem that may not be possible but I was wondering if it is possible to get a variable linkage of the function that created an instance from javascript.
for example, i'd like to be able to do something like this:
function MyObject(){
console.log(this) // traces out the instance
console.log(MyObject) // traces out the function
console.log(this.parentClass) //Would like this to trace out the function as well. (or a similar call like it)
}
var test = new MyObject();
Is this at all possible? Thanks!!
It's possible if the prototype objects on the functions haven't been replaced, or if the code replacing them keeps the linkage as it is by default.
The constructor property is (by default and convention) the property you're looking for:
var test = new MyObject();
console.log(test.constructor === MyObject); // "true"
Note all of the caveats above, though. For instance, this is perfectly valid (and not particularly atypical) code:
function MyObject() {
}
MyObject.prototype = {
foo: function() { /* ... */ },
bar: function() { /* ... */ }
};
This is a common pattern, although one I don't recommend. Instead of adding to the object referred to by the MyObject.prototype property (an object that was set up by the JavaScript engine when creating MyObject), that code is creating an entirely new object and assigning it to the prototype property, making it refer to the new object. If that has been done, then the constructor property has been broken, and you can't use it the way you want to use it.
The constructor property on the default prototype object on functions is a funny thing about JavaScript. It's defined quite clearly in the specification that it will be there (it's ยง13.2 if anyone wants to read up), but as far as I'm aware nothing in the JavaScript engine actually uses it. (It isn't, for instance, used for instanceof.)

JavaScript: Accessing objects in different classes

I have:
View1.prototype.function1 = function() {
this.test = "Hello";
};
And I want to call test in here:
View2.prototype.funcion2 = function() {
alert(View1.test);
};
However I get can error that View1 does not exist.
Ideas?
It's not clear to me what you are trying to do, the following may help (or not).
It's a convention in ECMAScript that variable names starting with a capital letter are constructors, e.g.
function View() {
...
}
To add a method to the constructor that is shared by all instances created from it, assign a function to the constructor's prototype:
View.prototype.f1 = function() {
this.test = "Hello";
};
Now to create an instance:
var view1 = new View();
and call the method:
view1.f1();
This calls View.prototype.f1 and passes view1 as its this value, so a test property is added with a value of "Hello":
alert(view1.test); // Hello
You can't call test since it's value is a string, and a string isn't callable. Only objects that implement the internal [[Call]] method, such as functions or host methods, are callable.
You may be struggling with prototype inheritance. If so, ask here. There are many articles on the web that attempt to explain it, but most are pretty awful.
PS: Firefox doesn't seem to like "function1" as an identifier.
View1.prototype.function1.call(View1);
View2.prototype.function2 = function() {
alert(View1.test);
};
Or change View1 to an object.

jQuery function declaration explanation

I've opened jQuery 1.7.1 library and wanted to study the code, but I've found a that functions are declared in strange way (for me). For example:
show: function() {
//some code here
},
I learned to define function on this way:
function show() {
//some code here
}
Can someone explain me why show function is not written on second way (like in most tutorials on internet)?
This is because it is within an object. Object Literals have their properties defined in this way:
{
name: value,
//OR
'name': value
}
Where value can be nearly anything such as a number, string, function, or even another object. In JavaScript you can also declare anonymous functions and assign them to a variable. In fact, the following declarations have the same effect:
//declares the myFunc1 function
function myFunc1() {}
//declares an anonymous function and assigns it to myFunc2
var myFunc2 = function() {};
//you can now call either like so:
myFunc1();
myFunc2();
So, combining those two concepts if I have an object and I want one of its properties to be a function I would do it like so:
var myObj = {
name: 'My Object',
init: function() {
return 'Initializing!';
},
version: 1.0
};
alert(myObj.init());
You would then get the output: Initializing!. Make sure to check out the great documentation and tutorials on the Mozilla Developer Network, including their JavaScript Tutorial Series
Hope this helps!
Writing it the first way is in essence, setting a function as property of an object.
For example:
// I can create a new empty object
var myObject = {};
// or I can create a new object with a basic property
var myObject = {
color: "blue"
};
// I can also create an object with methods (like jQuery)
var myObject = {
color: "blue",
showColor: function(){
alert(this.color);
}
};
// and you can use the object like this
myObject.showColor(); // calls the showColor method and will alert "blue"
This helps jQuery to encapsulate, namespace, and organize code.
Here are a couple of pretty good write-ups:
Why do you need to invoke an anonymous function on the same line?
http://en.wikibooks.org/wiki/JavaScript/Anonymous_Functions
http://www.evotech.net/blog/2008/07/javascript-object-literals-a-definition/
The first declaration, i.e., show: function, defines show to be a field in an object having type function. The second declares a function named show within the current scope (possibly global?)
they're being described as a js object function. In this case:
var jQuery = {
show: function(){
//some code here
}
}
so you access it like jQuery.show() for example.
I would say Chad's answer is most accurate for in depth research. You should look into them as they can revolutionize how you write js in a very clean way that is much less likely to conflict with other libraries.

In javascript functions, can you set this.function = function?

I have run into this jquery plugin and i quite understand how this works:
$.functionone = function(){
function setOptions(newOptions){
...
}
this.setOptions = setOptions;
}
What i dont understand is what does this actually do? this.setOptions = setOptions can you call a function without parenthesis? What is the relationship between this.setOptions and setOptions by itself?
Functions in JavaScript are objects like (nearly) everything else. When you do this:
this.setOptions = setOptions;
you're not calling the setOptions function, you're just assigning a reference to the function to a property, exactly like setting a property to any other object, like this:
var dt;
dt = new Date();
this.today = dt;
With functions, you'd do this so you can later call the function via the property (which sets up the this value to be the object the property's on, which is handy). It's a bit clearer what's going on if you use a different name for the property than for the function:
function functionName() { ... } // Declares the function
this.propertyName = functionName; // Sets the property
functionName(); // Calls the function (with `this` = the global object ["window", on browsers])
this.propertyName(); // Also calls the function (but with `this` = the object the property's on)
The pattern you identified, declaring a function and then separately setting a reference to it on an object, is frequently used to make sure the resulting function has a name. You can create a function and bind it to a property like this:
this.setOptions = function() {
...
};
...but then the function doesn't have a name (the property does, but not the function), which can be an issue when you're trying to debug because debuggers show you the names of functions in various contexts (call stacks, for instance). If a lot of your functions don't have names, even though the properties referring to them do, it makes debugging difficult. More about anonymous vs. named functions here. (There's also a difference in terms of when the function is instantiated, but going into it here would just complicate things.)
You'd think you could combine things, like this:
this.setOptions = function setOptions() { // <=== DON'T DO THIS
...
};
...but although that mostly works, it triggers a bug in Internet Explorer / JScript (it creates two different functions for that code, which is at best a memory waste and at worst a very subtle and time-wasting problem, as it was in this question).
The function setOptions is only called if you add parenthesis: setOptions(). If you do not add parenthesis, you have a reference to a function. This is just like a normal variable, only it contains a function reference instead of some other value.
If you set this.setOptions = setOptions, you make a function setOptions on the this object, which points to the same function as setOptions. That is, if you call it using this.setOptions(), the referenced function will be called.

Categories

Resources