JavaScript原型链

构造函数

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

引用类型

引用类型:数组、对象、函数

引用类型特点:

  1. 可自由扩展属性
//对象类型
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'
  1. 所有的引用类型(数组、对象、函数)都有一个 __proto__属性值为普通对象
  2. 所有的函数都有一个 prototype属性,属性值为普通对象
  3. 所有的引用类型(数组、对象、函数)的__proto__指向它的构造函数的 prototype属性,即
var obj = {}
console.log(obj.__proto__ === Object.prototype) //true
var arr = []
console.log(arr.__proto__ === Array.prototype) //true
  1. 当获取一个对象的属性时,若该对象没有此属性则会从该对象的__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>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值