functionPerson(firstname, lastname){ console.log(this);//Person{}, a new empty object this.firstname = firstname; this.lastname = lastname; console.log("this function is invoked"); }
var john = new Person('John', 'Doe'); console.log(john);
var jane = new Person('Jane', 'Doe'); console.log(jane);
new create a brand new empty object
the function Person() is called
this in the function is point to the new empty object
if the function doesn’t return a value, js engine return the new object
bigword alert : Function Constructors
A normal function that is used to construct objects.
‘this’ points to a new empty object.
the new empty object is returned from the funciton automatically.
後記: 我到現在才知道在js裡,new後面的是一個function…囧
6-58 Function constructor and ‘.prototype’
Recall
.prototype (property) is used only by functions
.property is the prototype of any object created(use ‘new’)
__proto__ is in all objects(includeing functions)
__proto__ is the prototype of the the object
.prototype 是改變所有new 出來的新object 的 prototype
看下面例子,john.__proto__ 指向 Person.prototype
good js code sets properties inside the function constructor. But methods are set on the prototype.
/* 0 : John 1 : Jane 2 : Jim myCustomFeature : cool! */
// use standard for loop to avoid this
6-63 Object.create and Pure Prototypal Inheritance
Pure Prototypal Inheritance
Object.create create a empty object with prototype point to the argument
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var person = { firstname : 'Default', lastname : 'Default', greet : function(){ return 'Hi' + this.firstname; // this point to the object person // if there is no this, js engine would find firstname in greet function's execution context // then find firstname in outer environment(in this case, it's global object) } }
var john = Object.create(person); console.log(john); // john has default name!! because of the prototype
//if object.create not exist, undefined // undefined is coerced to boolean if (!Object.create) { Object.create = function (o) { if (arguments.length > 1) { thrownewError('Object.create implementation' + ' only accepts the first parameter.'); } functionF() {} F.prototype = o; returnnew F(); }; }
var person = { firstname: 'Default', lastname: 'Default', greet: function() { return'Hi ' + this.firstname; } }
var john = Object.create(person); john.firstname = 'John'; john.lastname = 'Doe'; console.log(john);
// note that this is a Object, a created object // it exist in memory already classPerson{ constructor(firstname, lastname){ this.firstname = firstname; this.lastname = lastname; }