一、prototype(原型、原型对象)
-
定义: 每个函数天生自带一个属性prototype, 他是一个对象
,只要函数定义好以后,这个prototype 就出生了
-
构造函数也是函数,构造函数也有prototype ,我们可以向里面添加一些内容。
-
这个天生自带的prototype 对象里有一个属性叫做constructor ,这个constrctor 表示哪一个构造函数伴生的原型对象。
function Persor(name) { } Persor.prototype.say = function () { console.log('hello world'); } console.log(Persor);
二、js中 __ proto __
-
定义:每一个对象天生只带一个属性,叫做 __ proto __ ,指向所属构造函数的 prototype 属性
-
实例化对象也是一个对象,也有 __ proto __ 属性
function Persor() {} let a = new Persor(); console.log(a);
三、js中对象访问机制(上)
-
当你访问一个对象成员的时候,如果对象本身有直接返回对象结果给你,停止查询
-
如果对象本身没有,会自动去__proto__上访问
-
利用prototype和 __ proto __和对象访问机制
-
属性直接写在构造函数体内。
-
解决了构造函数的不合理。
-
方法书写在 构造函数的prototype 上。 使用构造函数创建一个有方法有属性的对象。
-
prototype作用: 就是为了书写一些方法给该构造函数的实例对象使用的。因为这个构造函数的每一个实例都可以访问这个构造函数的prototype
function Person(name,age) { this.name = name; this.age = age; } Person.prototype.say = function () { console.log('hello world'); } let a1 = new Person('xiaoha',32); let a2 = new Person('xiaoming',32); console.log(a1.say); console.log(a2.say);四 、面向对象写一个选项卡
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="1.js"></script> </head> <style> * { padding:0; margin:0; } .box { width: 600px; height: 300px; background-color: red; } .box > ul, .box li ,.box > ol { list-style: none; } .box > ul { width: 100%; height: 40px; background-color: #00bf00; } .box > ul li { line-height: 40px; background-color: silver; text-align: center; width: 200px; float: left; font-size: 20px; } .box > ol { height: 260px; width: 100%; overflow: hidden; } .box > ol li { height: 260px; width: 100%; line-height: 260px; background-color: silver; overflow: hidden; text-align: center; font-size: 20px; float: left; display: none; } .box li.active { display: block; background-color: deeppink; } </style> <body> <div class="box"> <ul> <li>1</li> <li >2</li> <li class="active">3</li> </ul> <ol> <li>1</li> <li >2</li> <li class="active">3</li> </ol> </div> </body> </html>function Tabs(ele, options = {type:'click'}) { this.ele = document.querySelector(ele); this.options = options.type; this.btns = this.ele.querySelectorAll('ul>li'); this.box = this.ele.querySelectorAll('ol>li'); this.change(); } Tabs.prototype.change = function () { this.btns.forEach ((item,index)=> { item.addEventListener(this.options || 'click',() => { this.btns.forEach ((item,index) => { item.className = ''; this.box[index].className = ''; }); this.btns[index].className = 'active'; this.box[index].className = 'active'; }) }); } new Tabs('.tabs',{type:'click'}); new Tabs('.tabs1', {type:'mouseover'});