Example of Properties vs. Methods in JS - javascript

I found a great description of the semantic difference between Properties and Methods (paraphrased, via http://www.webdeveloper.com/forum/showthread.php?133712-Properties-Vs.-Methods):
Properties are like nouns. They have a value or state.
Methods are like verbs. They perform actions.
A property can't perform an action and the only value that a method has is the one that is returned after it finishes performing the action.
e.g.
Property: door; Possible Values: open, closed
Method: openDoor; Action: to change the value of the door property to "open"
Creating an example: I understand this in theory but I can't come up with an example. Would it be possible to show me how the door/openDoor would look in actual Javascript code?

Really, you need to back up and read some of the links posted above. But as a quick example:
var house = {} ;
house.isDoorOpen = false ;
house.openDoor = function(){
house.isDoorOpen = true ;
}
Here house is the object. It has a property: house.isDoorOpen. Here, it is more like an adjective. Either the door is open (true) or closed (false). As it sounds, it describes a property of the house.
Also, it has a method openDoor (which is used like this: house.openDoor() ). That's something that it can do. In this case, the action openDoor affects the isDoorOpen property, making it true.

Let's look at how the javascript spec ECMA-262 describes the term property
http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.26
4.3.26 property
association between a name and a value that is a part of an object
NOTE Depending upon the form of the property the value may be
represented either directly as a data value (a primitive value, an
object, or a function object) or indirectly by a pair of accessor
functions.
4.3.27 method
function that is the value of a property
NOTE When a function is called as a method of an object, the object is
passed to the function as its this value.
Also
Javascript's definition of attribute is different from Java's
4.3.29 attribute
internal value that defines some characteristic of a property
for in, loops through an object's enumerable properties, and that includes its functions
http://eloquentjavascript.net/1st_edition/chapter8.html
"A function is called as a method when it is looked up as a property,
and immediately called, as in object.method()."
There does seem to be a more standard definition of property..
https://en.wikipedia.org/wiki/Property_(programming)#JavaScript
"A property, in some object-oriented programming languages, is a
special sort of class member, intermediate between a field (or data
member) and a method. .... Some object-oriented languages, such as
Java, don't support properties, and require the programmer to define a
pair of accessor and mutator methods instead."
In that more standard, non-javascript definition of property
C# has properties, and Java doesn't have properties

Object in JavaScript is just key-value pairs stored in a Hash. The difference between b/w property and method is that - property is a value stored in the hash key, whereas method is a function stored in the hash key.

Related

Why do some array methods rely on the global Array object?

I'm going through the MDN docs on arrays and when we want to test whether or not an object is an array we use isArray(). However, it's usage is very different to most of the other methods. When you use the regular syntax an error pops up:
console.log([1,2,3].isArray()); // TypeError: [1, 2, 3].isArray is not a function
Whereas this does work:
console.log(Array.isArray([1,2,3]))
I don't understand why isArray() (and a couple of other methods) rely upon some global object rather than just being accessible via the object in question. Why do some methods require the global array object?
rather than just being accessible via the object in question.
Because the whole purpose of Array.isArray is to be called on unknown objects. You don't know whether it's an array, you wouldn't know whether the method was accessible on it. The static method even works with values like null, which would inevitably throw an exception when you tried to invoke a method on them.
Digression:
isArray being callable as an instance method can work. In languages where everything is an object, like Smalltalk, Ruby or Io, even things like nil can have a isNil method. This approach has other problems of course, as with dynamic method dispatch every arbitrary object could overwrite the method and claim to be an array - on the other hand, that's exactly what we want for duck typing.
We could even simulate this in JS using Object.prototype.isArray = () => false; and Array.prototype.isArray = () => true;. Apart from failing on null and undefined, it still wouldn't work with objects that don't inherit from (our realm's) Object.prototype. And JavaScript "properties" that mix data fields and methods don't help either (consider the object parsed from the JSON string {"isArray":"maybe"}). We would always have to expect an exception from either .isArray not being a function, or from it being overwritten with a method that throws.
If we want to go for duck typing in JS, checking whether an object has an integer .length property is usually the way to go. Or more advanced, trying to follow the symbol-based iteration protocol. (That's what Array.from uses, for example).
But since arrays are a bit special in JS (with their magic .length property), we want a built-in reliable way to detect them, and that's what Array.isArray does.
Regarding other static Array methods: Array.of is pretty obvious, it's a factory function (like a constructor) and it can't be an instance method because there is no instance to work with in the first place. For Array.from the situation is a bit more like with isArray, a duck-typing Object.prototype.toArray approach could have worked as well but was dismissed for practical and design reasons.
See also Why were ES5 Object methods not added to Object.prototype?, Why use Object.prototype.hasOwnProperty.call(myObj, prop) instead of myObj.hasOwnProperty(prop)? and Why is it Object.defineProperty() rather than this.defineProperty() (for objects)? for similar discussions.
.isArray() is a static method, it exists on the Array "class" but not on each particular instance. Static methods are called like this: Array.isArray(). Object.create() is another example.
Methods like .map or .slice are not static, so they exist on each instance of the Array "class".
Array (denoted with a captial "A") indicates the JavaScript native Array object. [...] represents an instance of an array. As with many languages, some properties/methods are static. That is, they don't exist on instances only the type. This is often done when the value of the property or behavior of the method doesn't vary from instance to instance, so there's no need for it to be "instance-specific". Figuring out if something is an array, doesn't change from instance to instance (and frankly, doesn't make a lot of sense to ask an array instance if it is an instance of an Array).

Everything is an object?

At one popular blog, the author asked his audience what was their “Ah ha!” moment for JavaScript and most of the people said that it was realizing that everything in JavaScript is an object.
But being new to JS and programming in general I don't quite get what that means. It doesn't seam like it's related to actual JS Object - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
Or it does?
If it doesn't could you please explain what do they mean by "everything in JavaScript is an object".
Or it's all about OO Programming in general and reading something on this subject will help to understand it? Can you recommend what to read on this topic?
Go back to first principles.
What's an object? It's a software component that encapsulates state and behavior together into a single entity in memory.
By that definition, you can see where everything can be thought of as an object. Functional programmers make functions first class objects. Data folks would say that data, even that without behavior, can be thought of as an object (albeit not a very smart one).
I don't see what this changes.
JavaScript treats functions as objects.
I'm not sure what effect this insight will have on your programming.
What they mean, most likely, is that any data that can be assigned to a variable has properties (and therefore methods) that can be accessed in an object like fashion.
// strings
"asdf".length; // 4
"asdf".replace('f', 'zxc'); // "azxc"
// numbers
(10).toFixed(2); // "10.00"
// booleans
true.someProp; // undefined (point is it doesn't crash)
They even have prototypes they inherit from.
"omg".constructor; // function String() { [native code] }
String.prototype.snazzify = function() {
return "*!*!*" + this + "*!*!*";
};
"omg".snazzify(); // "*!*!*omg*!*!*"
However, these are primitives, and while they behave object like in a lot of ways, they are different from other "real" JS objects in a few ways. The biggest of which is that they are immutable.
var s = "qwerty";
s.foo; // undefined, but does not crash
s.foo = 'some val'; // try to add a property to the string
s.foo; // still undefined, you cannot modify a primitive
Do note though that functions are real mutable objects.
var fn = function(){};
fn.foo; // undefined
fn.foo = 'some val'; // try to add a property to the function
fn.foo; // "some val"
So while it's not technically true that "everything in JS is an object", under most circumstances you can treat them mostly like objects in that they have properties and methods, and can potentially be extended. Just be sure you understand the caveats.
NOT everything in JavaScript is an object.
All data in JavaScript must fall into one of six primitive types, or the object type. Primitive types includes boolean, null, undefined, string, number and symbol; everything that is not a primitive is an object.
This means functions are objects, arrays are objects, ES6 classes de-sugars into a function which are objects.
The confusion arises because primitive values have object wrappers. When you try to access the length property on the string literal, JavaScript creates a temporary object wrapper around the primitive and access the length property of that object wrapper. After the property has been retrieved, the object wrapper is discarded. This is known as autoboxing.
Essentially, it is implemented similar to the following:
const foo = "bar";
// When you run `foo.length`, it's similar to
tmp = String(foo);
tmp.length;
delete tmp;
Or
const foo = "bar";
(new String(foo)).length;
The string, number and boolean primitives have object wrappers, but null and undefined do not. So trying to access a property or method from those primitives would throw an error.
null.length; // Uncaught TypeError: Cannot read property 'length' of null
undefined.length; // Uncaught TypeError: Cannot read property 'length' of undefined
Not everything is an object in JavaScript. For example a number is not an object.
Different languages have different definition of "object". For JavaScript, the official definitions can be found in the ECMAScript Language Specification, which states:
In ECMAScript, an object is a collection of zero or more properties
each with attributes that determine how each property can be used (...) Properties are containers that hold other objects,
primitive values, or functions. A primitive value is a member of one
of the following built-in types: Undefined, Null, Boolean, Number,
BigInt, String, and Symbol; an object is a member of the built-in type
Object; and a function is a callable object.
So by this definition it is clear that primitive values (like numbers) are not objects. Even strings are not objects, which is different from most other OO languages.
So why do some people say "everything is an object"? You have to ask them! But I suspect it is because they are getting confused by the built-in objects Number, Boolean, String etc. which can be used as wrappers around the corresponding primitive values. This wrapping sometimes happen automatically, which can make primitive values look like object and for example allow you to (seemingly) access properties on primitives. But in reality the properties are on the wrapper object.
'ALMOST everything is an object' because the MAIN code-units are JS-objects. On primitives you can NOT add members for example as on all objects. My answer why JS-functions are JS-objects here: https://stackoverflow.com/a/24811539

Difference between Object.method(o) and o.method() [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why is it Object.defineProperty() rather than this.defineProperty() (for objects)?
I noticed that all the methods of a particular object can be called from the actual object instance, i.e., object.method(); or by passing the object to Object.method() as an argument. For example:
var a = ['one', 2, 3, 'four'];
a.reverse();
// OR
Array.reverse(a);
I seemed to get the same behaviour. I was wondering what the difference was and when one would be used over the other?
Object.method(o) looks on the Object object (Object is a real object in JavaScript) for a property called method and tries to call it passing in the variable o. During the call, this will be Object.
o.method() looks on the object referenced by the variable o for a property called method and tries to call it, not passing anything in. During the call, this will be o.
As you can see, they do quite different things.
I noticed that all the methods of a particular object can be called from the actual object instance...or by passing the object to Object.method() as an argument.
No, they cannot. Your example Array.reverse(a) fails on a standard implementation of Array because Array doesn't have a property called reverse and so it can't be called as a function. Edit: You note in the comments that it works in Firefox's scratchpad, and I just verified that. That means Firefox's SpiderMonkey JavaScript engine is applying a non-standard extension to Array which provides a static implementation of reverse. That's specific to Firefox's Array, not general to all objects. (If you make your own Foo, for instance, its prototype functions don't magically get added to Foo as well.)
The standard way to make the near-equivalent to a.reverse() would be via the prototype, like this:
Array.prototype.reverse.call(a);
That does work in standard engines. So let's look at what it does:
It gets the prototype property from Array.
It gets the reverse property from the object it got in #1.
It calls the function that property referenced using the Function#call feature of JavaScript function objects to make this be the argument you pass into call during the course of the function call.
When you create an array, the object gets an underlying prototype. That prototype is the object referenced by Array.prototype when the new array is created. So a has a reverse property because its underlying prototype has a reverse property.
Doing a.reverse() does this:
Gets the reverse property from the a object. Since (normally) a won't have its own property called reverse, standard JavaScript property lookup looks to a's underlying prototype. It finds the property there and uses its value.
Calls that function such that this is a within the call.
As you can see, the end result is the same provided that the underlying prototype of a and Array.prototype still refer to the same object. (It's possible for them not to, although in the case of Array or any other built-in, if someone replaced [as opposed to augmenting] Array.prototype, that would be a Bad Thing(tm).)

What is this strange JavaScript array syntax?

I am having some trouble searching google and stackoverflow for the answer to what this piece of JavaScript code is doing:
obj['e'+type+fn]( window.event );
To me this looks like an array element with an argument/parameter:
array[index](argument);
However, I can only guess at what this is doing. Is this equivalent to:
array[index]=argument
Which is assigning an argument to the array element?
If anyone could provide a simple/generic example of what this is doing that would be great.
I am attempting to decipher John Resig's addEvent() implementation. I'm not really looking for an explanation of this implementation or example related to it, but more like a dumbed-down example like MDC has done for call which uses some imagined products.
obj['e'+type+fn]( window.event );
This is just a way of accessing a property of an object. For instance, if you have an object
a = {
name: 'someName'
age: 20
};
You can access name by using a.name or, as above a['name'].
The reason he is using the [] notation is so that he can build the key from multiple strings.
Thus if type=click and fn=foo he's accessing obj.eclickfoo. Or obj['eclickfoo']
This property of the object must be a method as he's invoking it using (); so again, he's saying:
obj.eclickfoo( window.event );
or equivalent
obj['eclickfoo']( window.event );
This is what it is doing:
From the array obj, it takes the function with index 'e'+type+fn. It then executes it passing window.event as a parameter.
Remember that () invokes a function, and [] extract a value from an array.
obj['e'+type+fn] returns a function type. This is then executed with window.event as a parameter.
obj['e'+type+fn]( window.event );
Arrays can indeed use the "obj[...]" notation, but so can any object in JavaScript. And in this case, Resig is adding the property to any object, specifically for DOM objects.
obj['aVar'] is equivalent to obj.aVar. The advantage of the former is that it can also work with keywords which are reserved in JavaScript to have special meaning (e.g., obj['var'] if you defined a property called "var" on an object) and allows property names to be accessed dynamically, as in your example. Since type is a variable, you could not do obj.type since that would be finding a property exactly named "type", not finding a property with the name equal to the value of the type variable.
Since objects (or arrays) can hold functions as data, you can also use the invocation operator (the matching parentheses) on a function found inside of an object or array, as is done here--the property is accessed (which is a previously stored "method" or function on an object) and then invoked with the window.event object as a single argument.
Functions also have a built-in toString method on their prototype (which will get called in cases like this where you are are concatenating to a string, and therefore must want a string, as long as you don't set your own toString method on your function, since functions are also objects in JavaScript!). Resig's code is taking advantage of this, to define a new property, somewhat haphazardly which is normally a bad idea, but in a way which is pretty unlikely to clash with other applications also adding such a property.
So if document.body is the obj and if the type variable is set to "click" and "fn" is set to function () {alert('boo!');}", it will actually name a property on the document.body object as "eloadfunction () {alert('boo!');}". As he explains, creating this property (and then invoking it inside his own anonymous function), allows the function to be called with the normal behavior of any "this" keyword used inside--this will refer to the parent object, in this case obj, not to a global (unless obj is the global--i.e., the window object).

Every Object is a function and every function is Object - Which is Correct?

I was reading this link JavaScript_syntax
This seems to be cyclic - that every function is an Object and every Object itself is a function. Which is the atomic one? Can someone explain in a better way?
Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript. That means function inherits from object.
Object instances can contain more instances which can be functions. That's what we call a "method" (since it has an automatic this variable).
Since you can't "call" every Object instance, not every object is a function.
I think this concept is often misunderstood.
A utility to visualize JS types relationship http://jstype.herokuapp.com/#/home
Javascript Data Types
Primitive types - numbers, strings, booleans, null and undefined.
All non-primitive types are object:
var foo = { };
var foo = [1, 2, 3];
var foo = function abc() { return "hello world"; };
var foo = new Number(30);
var foo = new String("Hello World");
var foo = new Boolean(true);
var foo = new RegExp(/[foo]+/);
// All 'foo` are object.
All primitive types have a corresponding Constructor Function wiz. Array, Number, String, Boolean, RegExp. As all functions are objects, they are objects too. So we can call them Constructor Function Objects.
Most of the non-primitive type has prototype property where all inherited stuff lives. Math doesn't have prototype.
All objects inherit from Object.prototype which inherits from null.
object <- Object.prototype <- null
All native functions inherit from Function.prototype which inherits from Object.prototype.
function <- Function.prototype <- Object.prototype <- null
Arrays inherit from Array.prototype which inherits from Object.prototype.
array <- Array.prototype <- Object.prototype <- null
Must read MDN: Inheritance and prototype chain
To get confused Stackoverflow: prototype in JavaScript
Stack Overflow: Function prototype explained
Every function is an object. Objects can contain functions (methods) but an object is not necessary a function.
Also Function is always a property of an object.
This mean that all functions in JavaScript is always bound to an object. If you don't specify an object to bind a function to it's bound to the window object (Also called global functions)
..fredrik
It would be better to say that in JavaScript everything can be treated as an object, that includes primitive types as well as functions types; what the JavaScript interpreter does is that it automatically promotes your primitives and functions to their object wrapper types when you interact with them.
There is also a Function object, an a number of equivalent Wrappers for the other primitives in JavaScript, that means that you can even call methods on functions instances, like:
myFunction(someArg).call(this)
That being said, not every object is in fact a function.
As others have said, functions are objects that can be passed around by reference like other javascript objects. Not all objects are functions, only those that are declared as such.
You will often see methods declared like so:
var myFunc = function(foo, bar) {
...
};
This is to reinforce the fact that the method is a function object and as such it is a property of the object where it is defined, just like any other variable you might define with var.
This is the foundation of the most important feature in javascript, closure.
Every function is an Object.
I'm not an javascript expert, but I cannot see how every Object is a function. (I can see how every object could be a function, but that's different)
Quoting from Working with Objects - MDN Docs
section Using Object Initializers last paragraph:
"In JavaScript 1.1 and earlier, you cannot use object initializers. You can create objects only using their constructor functions or using a function supplied by some other object for that purpose. See Using a Constructor Function."
meant that all objects WERE functions! Specifically, upon evaluation, instances or instantiations of functions.
Literally, ALL objects of that vintage were created syntactically with constructs like:
"newobj = new constructFunctor(arg1,arg2){this.prop1=arg1 /* etc */}(val1,val2)"
AND in the string that makes the object "newobj" there is the word "constructFunctor", the name of a function. The statement is intentionally quoted to impress the fact that it must be eval()'d to be executed. Prior to execution "newobj" is "equated to" a function because the statement MUST have one and "is" one by virtue of "constructFunctor"'s literal existence to define newobj's value upon execution. The quoting, and not, is very intentional in order to elucidate this abstraction. However, because JavaScript DOES have an eval function, this abstraction is in fact intentionally incorporated into the JavaScript language.
The legacy of this is still fundamental to JavaScript, though some syntactic short cuts have been added as "object initializers" using the shorthand notation like: "no={}". That the paragraph quoted above is still resident in the current documentation IS significant for the very reasons noted.
Furthermore, JavaScript also exemplifies the fundamental paradigms of Functional Programming. This defines everything as a function using the abstractions of Recursive Function Theory and the Lambda Calculus! For instance 0(), 1(), 2(), ... are the constant nonary functions better known as 0,1,2,3, ...
JavaScript is completely consistent with a Functional Programming Style approach rather than the common OOPS (pun intended Object Oriented Programming Style).
Just for supplementary to Aaron Digulla's answer.
In javascript not every object is a function. But Object,Array,String and many other built-in objects are functions that used with new operator to create object. I think this is what confused most people.
javascript everything is a hashtable. Ryan Dahl said this in one of his talks. thats what json is also; a hashtable definition. thats why u can access an object using array notation or object property notation. the value of the hashtable can be a function as well which is a hashtable. or rather an associative array
type Object in the console u get { [native code] } which is a hashtable
Object is an abstract data given to a class and that class is assigned to an object. Object can have properties and properties can hold values and functions.
Or simply for the sake of making it easy to understand you can say that anything that is not primitive data type (number,string, boolean, unll & undefined) can be classified as an object.
the selected answer by Aaron Digulla's is not 100% correct because it says,
Anything that is not a primitive type (undefined, null, number,
string, boolean) is an object.
but a string is an object. That is why you can do things like:
myString="Hello World";
x = myString.length;
newString = myString.toUpperCase();
link = myString.link("http://www.hello-world.com/");
And many other methods can be applied to the string object.
You could also initialize the string like:
myString = new String("Hello, World!");
But because a string is also a datatype it is much easier to initialize it by just applying a value.
Not necessarily an answer to the question ... just a clarification/correction of Aaron Digulla's answer.
The selected answer is wrong. In JavaScript everything is a function, except primitive types. Object itself is a function which is called function Object(). Use for example the following code:
<script>
alert(Object);
</script>

Categories

Resources