New
New object is created with the constructor function.
Define class
var person = function (firstName) {
this.firstname = firstName;
};
Define method
Person.prototype.sayHello = function () {
console.log ("Hello, I ' m" + this.firstname);
Instance Object
var person1 = new Person ("Alice");
Object Invocation Method
Person1.sayhello ();//Logs "Hello, I ' m Alice"
Here's a question as to why the SayHello method is defined on Person.prototype, and prototype is something.
Prototype is the magic of JavaScript oop. JavaScript's object-oriented, inheritance and other implementations revolve around the prototype attribute.
In JavaScript, only function (a function in JavaScript is also an object) has the prototype attribute. Defines a function whose prototype default is an empty object, that is, {}.
var test = function () {return ' Haha ';};
Console.log (Test.prototype); // {}
function has the prototype attribute, the object created by the function has the concept of a prototype. Person1 is constructed from the person function, so Person1 's prototype is person.prototype. JavaScript uses __proto__ to point to the object's prototype.
Console.log (Person.prototype)//{sayhello: [function]}
console.log (person1.__proto__)//{sayhello: [function]}
From this you can sum up what new has done:
1. Create Instance Object Person1
2. Call the constructor (person) to initialize the Person1 member variable (firstname).
3. Specifies the prototype of the instance object as the Person.prototype object. That is, person1.__proto__ points to Person.prototype. object.create ()
The function of Object.create (o) is to create an empty object, the prototype of which is parameter o:
var o = object.create (null);
Console.log (o); {}
o.name = ' jian ';
var O2 = Object.create (o);
Console.log (O2); // {}
O2 is an empty object, but o2.name output ' jian ', the Name property is not found on the object O2, but found on the prototype O.
This can be summed up object.create () did:
1. Create empty Object {}
2. Specifies that the prototype of the empty object {} is a object.create () parameter.