美文网首页
深入理解JavaScript对象

深入理解JavaScript对象

作者: LeeYee11 | 来源:发表于2017-04-16 19:32 被阅读0次

对象的种类

函数对象与普通对象

  //普通对象
  var obj_a=new Object();
  obj_a.key='value';
  var obj_b={'key':'value'};
  var obj_c=new foo();
  function foo(){this.key='value';}

  //函数对象
  var func_a=function(param){doSomething(param)};
  var func_b=new Function('param','doSomthing(param)');
  func_c(param){doSomething(param);}

构造函数与原型对象

//假设有类A
//构造函数
function A (param) {
   this.attribute = param;
   this.getAttribute = function(){
      return this.attribute;
   }
   this.setAttribute = function(other_param){
      this.attribute = other_param;
    }
}
//创建实例a
var a = new A('monkey');
console.log(a.getAttribute()); //output: monkey
console.log(a.constructor);  //output: function A(param){...} 构造函数的内容
//原型对象
function A () {};
A.prototype.attribute = 'monkey';
A.prototype.getAttribute = function(){
  return this.attribute;
}
A.prototype.setAttribute = function(other_param){
  this.attribute = other_param;
}
//原型对象即A.prototype
//创建实例
var a=A.prototype;
console.log(a.getAttribute()); //output: monkey
console.log(a.constructor); //output: function A(){} 构造函数体内没有内容

prototype 与__proto__

  • prototype
  • 仅函数对象含有prototype
//f.prototype.constructor == f

var f=function(){}; //函数对象
console.log(f.prototype);//output: f{}

var o={}; //普通对象
console.log(o.prototype);//output: undefined

//个人的理解是prototype是类的默认实例
//此处f类的默认实例就是f{}
  • prototype中的值是类的默认值,当某个属性在类定义中找不到时,会从prototype中寻找
function F (param) { this.attribute = param };
F.prototype.anotherAttribute = 'another one';
var f = new F('one');
console.log(f.anotherAttribute); // output: another one
  • __proto__
  • 每个对象都含有__proto__(规范属性应为[[prototype]])
//a为实例,A为构造函数
//a.constructor=A
//a.__proto__=A.prototype
//a.__proto__=a.constructor.prototype(除了用Object.create()构造的对象)
var f=function(){}; //函数对象
console.log(f.__proto__);//output: function()
//任何函数对象的构造函数的默认实例都是function(),       
 
var o={}; //普通对象
console.log(o.__proto__);//output: Object{}
//任何普通对象的构造函数的默认实例都是Object{}
  • 原型链
    每一个对象指向自己的__proto__对象形成的链条,找到最后的值是null
var A = function(){};
var a = new A();
console.log(a.__proto__); //output: A {}
console.log(a.__proto__.__proto__); //output: Object {}
console.log(a.__proto__.__proto__.__proto__); //output: null
  • 关系
个人总结的函数对象原型链图
  • 构造函数
    //除了普通对象,所有函数对象的构造函数都是Function类型
Math.constructor==Object
JSON.constructor==Object   
//xxx表示函数对象,包括Object和自定义函数对象
xxx.constructor==Function

//因此
Math.__proto__==Object.prototype
JSON.__proto__==Object.prototype
xxx.__proto__==Function.prototype
  • 一切皆对象,包括函数
    Function.prototype.__proto__==Object.prototype

相关文章

网友评论

      本文标题:深入理解JavaScript对象

      本文链接:https://www.haomeiwen.com/subject/pkwaattx.html