构造函数
function Person(name,sex){
this.name = name
this.sex = sex
}
var xiaoming = new Person('ming',0)
var o = {} // 相当于var o = new Object() 因此 typeof o 为 Object
var a = [] // 相当于var a = new Array() 因此 typeof a 为 Object
function Foo(){} // 相当于var Foo = new Function() 因此 typeof Foo 为 Object
引用类型
引用类型:数组、对象、函数
引用类型特点:
- 可自由扩展属性
//对象类型
var obj = {name:'zheng'}
obj.sex = 0
//数组类型
var arr = [1,2,3]
console.log(arr) //[1, 2, 3]
arr.name = 'zheng'
console.log(arr)//[1, 2, 3, name: "zheng"]
//函数类型
function fun(){}
fun.name = 'zheng'
- 所有的引用类型(数组、对象、函数)都有一个
__proto__
属性值为普通对象 - 所有的
函数
都有一个prototype
属性,属性值为普通对象 - 所有的引用类型(数组、对象、函数)的
__proto__
指向它的构造函数的 prototype属性,即
var obj = {}
console.log(obj.__proto__ === Object.prototype) //true
var arr = []
console.log(arr.__proto__ === Array.prototype) //true
- 当获取一个对象的属性时,若该对象没有此属性则会从该对象的
__proto__
中寻找(即它的构造函数的prototype)
function Fun(name,sex){
this.name = name
this.sex = sex
}
Fun.prototype.getName = function(){
console.log(this.name)
}
var f = new Fun('zheng',0)
f.getSex = function(){
console.log(this.sex)
}
f.getName()//zheng
f.getSex()//0
instanceof
instanceof用于判断一个引用类型属于哪个构造函数方法
var arr = []
var obj = {}
function Fun(){}
let f = new Fun()
console.log(arr instanceof Array)//true
console.log(arr instanceof Object)//true
console.log(Fun instanceof Function)//true
console.log(f instanceof Fun)//true
// 以下同样成立
console.log(arr instanceof Object)//true
console.log(arr instanceof Object)//true
console.log(Fun instanceof Object)//true
console.log(f instanceof Object)//true
原型链demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="div" style="width: 100px;height: 100px;border: 1px solid red"></div>
<script type="text/javascript">
function GetElementById(id){
this.element = document.querySelector(id)
}
GetElementById.prototype.html = function(text){
if (text) {
this.element.innerHTML = text
return this
}else{
return this.element.innerHTML
}
}
GetElementById.prototype.on = function(type,fn){
this.element.addEventListener(type,fn)
return this
}
var div = new GetElementById('div')
div.html('<h1>点我</h1>').on('click',function(){
alert('┭┮﹏┭┮')
})
</script>
</body>
</html>