Properties of JavaScript Function Objects

Properties of Javascript function objects

I'm not sure this will answer your question but may give you some insight. Consider the following example:

var Person = (function () {
var Person = function (name) {
this.name = name;
}

Person.greet = function () {
console.log("Hello!");
}

Person.prototype = {
greet: function () {
console.log('Hello, my name is ' + this.name);
}
};
return Person;
})();

var bob = new Person("Bob");

Person.greet(); // logs "Hello!"
bob.greet(); // logs "Hello, my name is Bob

The function object "Person" has a direct 'greet' property that is a Function. OOP-wise, you can almost think of that as a static method that can be called directly from the Person Function (Person.greet()). Once you "instantiate" a person object from the Person constructor, that new object "bob" now references it's methods from the Person.prototype object. Now when you call bob.greet(), it uses the greet function in the prototype object.

Hope that helps.

JavaScript - function as an object property

  1. Yes, katana is an object (created using the { ... } notation). "use" is the name of the property of the object whose value will be the anonymous function (which is also an object).

  2. The function inverts the value of isSharp (so from true to false or false to true).

  3. It is asserting that isSharp is something which does not evaluate to true (this is nearly everything except undefined, null, false, 0, etc). In this case, since isSharp is always either true or false, it is asserting that it is false.

The main point (and cool part) of the sample is this line:

katana.use();

This first fetches the value of the "use" property from the katana object (that's the katana.use part). The value is the anonymous function from before. Then, that function is executed (that's the () part). The really cool part is that it is executed on behalf of the katana object -- that means this in the anonymous function is a reference to the katana object when it's called that way.

How to get all the properties assigned to the function object in javascript?

Functions are special type of Objects in JavaScript.

Unlike other programming languages, functions are special type of Objects in JavaScript. They have their own methods (viz. bind, call, apply and a hell lot more) like other objects do. Therefore, when you assign a prop a to your func, you are not creating a new func object. Instead, it's the same func object (function object) and you are just creating a new prop func.a on it. Read this for more info. Also, you can do something like the following to print all the props you have assigned to a function object (or any object in JS):

for (var prop in func) {
console.log(prop); // This will print 'a' in your case
}

Javascript object properties and functions

Sure, Ben.

This sort of gets to the bottom of the dynamism of JavaScript.
First, we'll look at basics -- if you're coming from a place where you understand class-based languages, like, say, Java or C++/C#, the one that is going to make the most sense is the constructor pattern which was included very early on:

function Egg (type, radius, height, weight) {
// private properties (can also have private functions)
var cost = (type === "ostrich") ? 2.05 * weight : 0.35 * weight;

// public properties
this.type = type;
this.radius = radius;
this.height = height;
this.weight = weight;
this.cracked = false;

// this is a public function which has access to private variables of the instance
this.getCost = function () { return cost; };
}

// this is a method which ALL eggs inherit, which can manipulate "this" properly
// but it has ***NO*** access to private properties of the instance
Egg.prototype.Crack = function () { this.cracked = true; };

var myEgg = new Egg("chicken", 2, 3, 500);

myEgg.cost; // undefined
myEgg.Crack();
myEgg.cracked; // true

That's fine, but sometimes there are easier ways of getting around things.
Sometimes you really don't need a class.

What if you just wanted to use one egg, ever, because that's all your recipe called for?

var myEgg = {};  // equals a new object
myEgg.type = "ostrich";
myEgg.cost = "......";
myEgg.Crack = function () { this.cracked = true; };

That's great, but there's still a lot of repetition there.

var myEgg = {
type : "ostrich",
cost : "......",
Crack : function () { this.cracked = true; }
};

Both of the two "myEgg" objects are exactly the same.

The problem here is that EVERY property and EVERY method of myEgg is 100% public to anybody.

The solution to that is immediately-invoking functions:

// have a quick look at the bottom of the function, and see that it calls itself
// with parens "()" as soon as it's defined
var myEgg = (function () {
// we now have private properties again!
var cost, type, weight, cracked, Crack, //.......

// this will be returned to the outside var, "myEgg", as the PUBLIC interface
myReturnObject = {
type : type,
weight : weight,
Crack : Crack, // added benefit -- "cracked" is now private and tamper-proof
// this is how JS can handle virtual-wallets, for example
// just don't actually build a financial-institution around client-side code...
GetSaleValue : function () { return (cracked) ? 0 : cost; }
};

return myReturnObject;
}());

myEgg.GetSaleValue(); // returns the value of private "cost"
myEgg.Crack();
myEgg.cracked // undefined ("cracked" is locked away as private)
myEgg.GetSaleValue(); // returns 0, because "cracked" is true

Hope that's a decent start.

Accessing function object's properties from inside the function body

arguments.callee is the function itself and doesn't get affected by the name of the function.

var f = function() { 
console.log(arguments.callee.a);
};
f.a = 'Test';
f();

Is `Object` a function in JavaScript?

You seem to be confused between "object" (the data structure) and Object (the function).

An object is a concept in JavaScript that is a generic container for some data. An object contains properties with keys and associated values.

In JavaScript, everything that is not a primitive is an object. This includes functions, which are basically a special type of object that can be "called" with the () syntax.

JavaScript provides a number of built-in functions that have various purposes. Two such functions happen to be called Object and Function. So in other words Object is a function and thus also an "object" (data structure).

Let's take your function Foo as an example:

function Foo() {
var a = "3";
}

Foo is a function. This means that Foo can be called, eg. var f = Foo(). In this case f will be undefined since Foo doesn't return anything.

Because Foo is a function, it is also an object. This means we can also add and read properties from it:

Foo.bar = 5;
Foo.bar++;
console.log(Foo.bar); // prints 6

Please note that this "object" part of Foo is not related to the contents of the function. That means that the code you declared (var a = "3") is irrelevant. You cannot access var a in any way here because it does not exist until you call the function. If you were to do Foo.a, you are not manipulating var a inside the function; you are working with the property a on the object Foo.

You can however do it the other way around and access properties on Foo inside of the function:

function Foo() {
var a = "3"; // a is local to this scope, you cannot get to it from outside
console.log(a); // prints 3 - local variable a is accessible inside the scope of this function
console.log(Foo.a); // prints 5 - a is a property on object Foo, and is accessible here
}
// var a inside Foo cannot be accessed here
Foo.a = 5;
Foo();

Edit: Re. your question regarding "this" in the comments. this is a special keyword in JavaScript that refers to an object. However, this object is not the function itself, it is a new object that is created when you call a function using the new keyword:

function Bar() {
this.a = 10;
console.log(this == Bar); // prints false
}
var bar = new Bar();
console.log(bar.a); // prints 10

A function that is meant to be called with the new keyword is referred to as a "constructor function". Object and Function are both examples of constructor functions, which is why their names start with an uppercase letter (a convention in JavaScript).

When you create an object with a constructor function, the property prototype of this function is used as the prototype (accessible through __proto__) of the created object.

console.log(bar.constructor == Bar) // prints true
console.log(bar.__proto__ == Bar.prototype) // prints true

this is also used for other things, but that is a broad subject and way out of scope for this question.

How javascript function objects are created and get their internal properties

You are experiencing the classic confusion between the prototype property, and an object's prototype. They are entirely different, although related.

The prototype property of a function is an object which is set as the prototype for objects created using that function as a constructor. Initially, it is an empty object except for a constructor property pointing back to the constructor.

The prototype (not the prototype property) of an object is set when the object is created, from the prototype property of the constructor. It may be referred to as the __proto__ property, or retrieved via Object.getPrototypeOf.

In your case, Person has a prototype property which is initially basically empty except for the constructor property. It has nothing to do with the prototype property of the Function object. It becomes the prototype of instances of Person created via new Person(). You can add your own methods and properties to it, as in Person.prototype.alert = function() { alert(this.name); };.

Entirely separately from its prototype property, Person has a prototype which comes from the prototype property of the Function object, since Person is implicitly created using the Function constructor. That's where Person gets bind etc. (although if you intend to use Person as a constructor, I doubt if you'd find much use for bind).

To get a better idea, try the following in your console:

function Person() { }
Person.__proto__ === Function.prototype // true
Function.prototype.isPrototypeOf(Person) // true
Object.getPrototypeOf(Person) === Function.prototype // true

How do I assign a function to the property of a Javascript object?

If the code was written like this, I bet you understand it:

var player1 = {
name: "Chris",
score: 1000,
rank: 1,
playerDetails: function() { alert('The name is '+ this.name) }
};

var player2 = {
name: "Kristofer",
score: 10000,
rank: 2,
playerDetails: function() { alert('The name is '+ this.name) }
};

The author of the code wanted to define the "playerDetails()" function once.

Another way of showing this in a simplified manner is:

var player1 = {
name: "Chris",
score: 1000,
rank: 1
};

player1.playerDetails=function() { alert('The name is '+ this.name) }

var player2 = {
name: "Kristofer",
score: 10000,
rank: 2
};

player2.playerDetails=function() { alert('The name is '+ this.name) }

So if you wanted to optimize the code above by only writing the playerDetails function once, it would look like the code in your post.

If I had written the code block, I might have written it like this: (which is easy to read)

function playerDetailsFunc() {alert('The name is '+ this.name) }

var player1 = {
name: "Chris",
score: 1000,
rank: 1,
playerDetails: playerDetailsFunc
};

var player2 = {
name: "Kristofer",
score: 10000,
rank: 2,
playerDetails: playerDetailsFunc
};


Related Topics



Leave a reply



Submit