Prototype in JavaScript
A prototype is nothing but an object from which other objects inherit their properties and every object in JavaScript has a prototype by default.
Objects in JavaScript is primitive data type which may be Null, Undefined, Number, String or Boolean. It stores the values in form of Key-Value pairs and each pair is called as the property while function are called as methods.
Name of the property of any object can be a string or a number, but if the we are defining the property name like a number than we can not access it by just putting the dot after the object, but can access it like child with the bracket notation.
To understand this, we have the following code :
<script type="text/javascript">
function getType() {
var myObject = new Object({123: "Emp Name", favoriteAuthor: "Author Name"});
alert(myObject["123"]);
}
</script>
Object Data Properties Have these following attributes :
- Configurable Attribute: Specifies whether the property can be deleted or changed.
- Enumerable: Specifies whether the property can be returned in a for/in loop.
- Writable: Specifies whether the property can be changed.
Note : These three attributes are set to true by default
To add function as a property with help of prototype , we can do that in following way :
var myObject = new function(name){
this.name = name;
}
myObject.prototype.prinName = function(){
console.log(this.name);
}
0 Comment(s)