码迷,mamicode.com
首页 > 其他好文 > 详细

关于new操作符

时间:2017-10-03 09:32:00      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:通过   一个   local   his   构造函数   function   typeof   turn   style   

在使用构造函数需要生成实例对象的情况下,我们要使用到new操作符,那么new操作的过程中到底发生了什么?

function Ele(id) {
  this.ele = document.getElementById(id);
}

Ele.prototype.width = function(val) {
  if(typeof val === ‘number‘ && !isNaN(val)) {
    this.ele.style.width = val + ‘px‘;
   return this;
  }  
}

Ele.prototype.height= function(val) {
  if(typeof val === ‘number‘ && !isNaN(val)) {
    this.ele.style.height= val + ‘px‘;
    return this;
  }  
}
Ele.prototype.bgcolor= function(val) {
  this.ele.style.backgroundColor= val;
  return this;
}


let box = new Ele(‘box‘);

box.width(100).height(100).bgcolor(‘red‘)  //我们发现box是一个实例化的对象,拥有了构造函数Ele的方法,那么new操作的执行过程中到底发生了什么呢?

// 1、new操作中首先创建一个空对象o,将空对象o的__proto__属性指向构造函数的prototype属性上,形成一条原型链,o.__proto__ = Ele.prototype
// 2、将构造函数的上下文指向空对象,并且执行构造函数中的命令,可以当作是 Ele.call(o,‘box‘), 在这里会发生的操作是  o.ele = document.getElementById(‘box‘) 
// 3、最后将这个新构建的对象o返回,return o,这样box就得到了一个原型对象是Ele.prototype,并且拥有了一个ele属性的对象,当然现在box也就是o了,它们都是指向同一个对象的。
// box在使用width方法时,先在自身属性上寻找width,发现找不到,就到自己的原型对象上Ele.prototype上去寻找这个方法,然后就找到了width方法,所以box能使用width方法
box  // {ele: div#box}
Object.getPrototypeOf(box) // {width: f, height: f, bgcolor: f, constructor: f} ,我们通过这个方法来获取原型对象,因为__proto__是属于浏览器内置的


//最后的小tips:如果构造函数中返回了一个对象,那么前面所说的全都没用啦,box就等于返回的对象,如果返回的是基本类型的数据,不是对象的话,那么还是按照上面所说的返回o对象
function Ele(id) {
  this.ele = document.getElementById(id);
 return []; 
}

Ele.prototype = {
 constructor: Ele,
 width: function(){},
 height: function(){},
  bgcolor: function(){}
}
let box = new Ele(‘box‘);

box // [] ,我们发现box是一个空数组,它也没有了width,height等方法
Object.getPrototypeOf(box) // [constructor: ?, toString: ?, toLocaleString: ?, join: ?, pop: ?, …] 它变成了数组的prototype ,不再指向Ele.prototype

 

关于new操作符

标签:通过   一个   local   his   构造函数   function   typeof   turn   style   

原文地址:http://www.cnblogs.com/subyang/p/7623206.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!