functionsoldier(ID) { var temp_obj = {};// ① new helps us a temp_obj temp_obj.__proto__ = soldier.prototype;//② new helps us bind the prototype temp_obj.ID = ID; temp_obj.life = 42; return temp_obj;//③ new helps us return the temp_obj; }
functionTest(name) { this.name = name } Test.prototype.sayName = function () { console.log(this.name) } const t = new Test('cxk') console.log(t.name) // 'cxk' t.sayName() // 'cxk'
Test if we return a value in the function:
1 2 3 4 5 6
functionTest(name) { this.name = name return1 } const t = new Test('cxk') console.log(t.name) // 'cxk'
So if we return a value in the function, there is no difference.
Test if we return an object in the function:
1 2 3 4 5 6 7 8
functionTest(name) { this.name = name console.log(this) // Test { name: 'yck' } return { age: 26 } } const t = new Test('yck') console.log(t) // { age: 26 } console.log(t.name) // 'undefined'
So if we return an object, the new doesnt effect.
1 2 3 4 5 6
functioncreate(fun, ...args) { let obj = {};//create a temp_obj Object.setPrototypeOf(obj, fun.prototype)//bind the temp_obj to prototype let result = fun.apply(obj, args)//bind obj to construction function return result instanceofObject ? result: obj; }
Then we test function create :
1 2 3 4 5 6 7 8 9 10 11
functionTest(name, age) { this.name = name this.age = age } Test.prototype.sayName = function () { console.log(this.name) } const a = create(Test, 'cxk', 21) console.log(a.name) // 'cxk' console.log(a.age) // 21 a.sayName() // 'cxk'