Object.function Help

0 Landon Luman · May 19, 2015
What I want to do, is make a function that can take the value from an object before it, like this
object.function();

// or

function swag() {
 var object = (how ever way you plan to help me);
 return object + "it worked";
}

var foo = "super swag maestro";

foo.swag();

is there a way to make this function work?

object.function()

Post a Reply

Replies

Oldest  Newest  Rating
0 Ali Hassan · May 19, 2015
ok I'm not really sure of what you want to do this for a single object or to any object so here it is:

if you want your object to have this function you need to define it into the scope of this object as a method of it like so

var obj = {

attr1: "value 1",
attr2: "value 2",
//other attributes or methods
swag: function(){

}

}
+1 Ali Hassan · May 19, 2015
ok I'm not really sure of what you want to do this for a single object or to any object so here it is:

if you want your object to have this function you need to define it into the scope of this object as a method of it like so

var obj = {

attr1: "value 1",
attr2: "value 2",
//other attributes or methods
swag: function(){
// Your code here
// you can also access the object value with the this keyword.
console.log(this) // will log the object itself into the console

}

}

then you can just call that function like you want
obj.swag(); //will log the obj to the console.


another thing...if you plan to use this function across all objects(meaning like arrays , your object or any other objects) then its kinda tricky .... see all objects whether you defined them or they're already defined are an instance of the Object object so if you plan to use this function across all objects you can define it in the Object object scope like so:

Object.prototype.swag = function(){

console.log(this);

};

var obj = {

val: "Hello"

};

obj.swag(); // will console obj to the console

however in the second method your function dont really know which type of objects its dealing with so it will become harder to access the properties of the object you want within you function without any conditional statements that can take a long time...so if you just want to call function on an object follow the first method and define that method in the object scope itself and not in the Object object scope......if i missed your point please tell me and explain a little more about what you want :D
0 Landon Luman · July 5, 2015
It's ok, this worked fine! Thanks :D
  • 1

Javascript

107,330 followers
About

A scripting language that is added to standard HTML to create interactive effects, apps, games for the browser.

Links
Moderators