How is it possible to instantiate from a Javascript function?
Q1) How is this possible?!
function employer(name) { this.name = name;};
var fred = new employer('Fred');
Isn't employer a function rather than a class?
Q2) What does
employer.prototype
signify?
and finally
Q3) How d开发者_开发技巧oes this work?
employer.prototype.salary = null;
fred.salary = 2000;
Can someone please give simple explanation? Please :)
As you asked for a simple explanation, here we go:
Q1) This is possible because JavaScript functions are first-class (i.e. they are objects, and you can create new
objects).
Q2) A prototype
is an object from which other objects inherit properties. Properties of an objects prototype will be available to all instances of that object.
Q3) This means that all instances of employer
will have a property salary
with the value null
. The instance of employer
called fred
simply overrides that initial null
value with 2000
. It's the same salary
property though (when you use a property, the scope chain is searched until a match is found. In this case, a match is found on the object prototype).
Quick example:
function employer(name) { this.name = name;};
employer.prototype.salary = 1000;
var fred = new employer('Fred');
var jim = new employer('Jim');
console.log(fred.salary) //Prints 1000 because employer.prototype.salary == 1000
fred.salary = 2000;
console.log(fred.salary) //Prints 2000 because fred's salary has been changed
console.log(jim.salary) //Prints 1000 because jim's salary is still referencing the prototype
fred.age = 30;
console.log(fred.age) //Prints 30
console.log(jim.age) //Prints undefined (age is a property of fred, not employer.prototype
精彩评论