JavaScript new对象的四个过程

new 一个对象

function Person(name, age) {  
	this.name = name;  
	this.age = age;   
}  
var person = new Person("hellen", 23);

 

1、创建一个空对象

var obj = new Object(); 

2、让Person中的this指向obj,并执行Person的函数体

var result = Person.apply(obj,arguments);  

3、设置原型链,将obj的__proto__成员指向了Person函数对象的prototype成员对象

obj.__proto__ = Person.prototype; 

4、判断Person的返回值类型,如果是值类型,返回obj。如果是引用类型,就返回这个引用类型的对象。

if (typeof(result) == "object") 
	person = result;  
else
	person = obj;

 

function Person (name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.sayName = function () {
  console.log(this.name);
};
var person = new Person('Hellen', 23);
person.sayName();
console.log(person instanceof Person);

function New () {
  let obj = new Object();
  let fn = [].shift.call(arguments);
  let args = arguments;
  var ret = fn.apply(obj, args);
  obj.__proto__ = fn.prototype;
  return typeof ret === 'object' ? ret : obj;
}
let person1 = New(Person, 'Bob', 23);
person1.sayName();
console.log(person1 instanceof Person);

  

 

posted @ 2019-06-11 18:08  不知不觉、  阅读(2215)  评论(0编辑  收藏  举报