程序员

Function() 和 Object()

2018-04-26  本文已影响116人  周紫一
image.png

对应代码

function Foo(name, age){
    this.name = name
    this.age = age
    this.getName = function(){
        return this.name
    }
}
Foo.prototype.sex = "man"
var foo = new Foo("四月天", 18)
console.log(foo)

打印结果:

一个Foo类型的对象:

image.png

展开:

foo对象的 [[prototpye]] 属性指向Foo.prototype,Foo.prototpye是一个Object类型的对象

image.png

Foo.prototope对象属性列表:

image.png

sex属性是手动添加的
constructor作为一个构造器指向了Foo这个Function(其实吧,本人理解constructor和function是一个概念
[[prototype]]属性作为Javascript中对象的隐式原型,每个对象具有的

SO:
foo对象的属性有6个
构造器中3个(name,getName,age)
构造器原型中属性sex算1个
构造器属性算1个
隐式原型[[prototype]]算一个

for(i in foo){
    console.log(i)
}

参与for in 遍历的有4个,[[prototype]]和constructor不参与遍历个 image.png

继续深入:展开Foo.prototype.[[prototype]]也就是Object.prototype

image.png

可以看出:
构造器(function)的原型的隐式原型指向了Object.prototype对象
然而这个对象Object.prototype是没有[[prototype]]属性的,或者说对象Object.prototype的[[prototype]]属性指向NULL
也就是说Object.prototype是继承的原点

Object.prototype的属性: 具体API去mdn查一下就OK了

constructor:ƒ Object()
hasOwnProperty:ƒ hasOwnProperty()
isPrototypeOf:ƒ isPrototypeOf()
propertyIsEnumerable:ƒ propertyIsEnumerable()
toLocaleString:ƒ toLocaleString()
toString:ƒ toString()
valueOf:ƒ valueOf()
__defineGetter__:ƒ __defineGetter__()
__defineSetter__:ƒ __defineSetter__()
__lookupGetter__:ƒ __lookupGetter__()
__lookupSetter__:ƒ __lookupSetter__()
get __proto__:ƒ __proto__()
set __proto__:ƒ __proto__()

展开Foo.prototype.constructor

image.png image.png
  1. Foo.prototype.constructor指向了它自身
  2. Foo.prototype.constructor.[[prototype]]指向了Function.prototype
    也就是Foo.[[prototype]]指向了Function.prototype

现在是时候展开Function.prototype了

image.png

现在看到的这些方法是不是很亲切,没错,就是我们经常用的apply,call,bind,toString
Function.prototype.[[prototype]]当然是指向Object.prototype
Function.prototype.constructor指向他自身喽

apply:ƒ apply()
arguments:(...)
bind:ƒ bind()
call:ƒ call()
caller:(...)
constructor:ƒ Function()
length:0
name:""
toString:ƒ toString()
Symbol(Symbol.hasInstance):ƒ [Symbol.hasInstance]()
get arguments:ƒ ()
set arguments:ƒ ()
get caller:ƒ ()
set caller:ƒ ()
__proto__:Object
[[FunctionLocation]]:<unknown>
[[Scopes]]:Scopes[0]

但是Object和Function的构造器是什么东东

直接打印试试:

console.log(Object)
console.log(Function)

结果是这样的:


image.png

也就是说直接打印是看不到的,因为底层是C++代码

别急:前面一直在说function=constructor,只要查看Object和Function的构造器就好了呀

查看Object构造器: image.png

看到create(),assign(),是不是很熟悉,没错就是他

查看Function()也就是查看Function.prototype.constructor image.png

结果发现这哥们里面干干净净的啥也没有,嘿嘿
有一点要注意:Function.[[prototype]] == Function.prototype

:总结:

constructor(function)和prototype和[[prototype]]的关系
1.不管是什么对象都会有[[prototype]]属性
2.constructor和prototype互为属性,相互引用
3.普通的对象是没有prototype属性的,只有构造器有prototype属性,并且构造器的prototype属性是一个普通对象。

也就是说,js里面只有两种对象类型Function对象,普通对象(自己取得名,或者你叫他prototype类型对象也可以吧)

但是有一个例外 Function Window ()的proto为EventTarget.prototype

<!DOCTYPE html>
<html>
</html>

<script>
    console.log(Window);
    console.log("==================");
    console.log(window);
</script>   
image.png image.png
上一篇 下一篇

猜你喜欢

热点阅读