千鋒教育JavaScript全套視頻教程(10天學(xué)會(huì)Js,前端javascrip

? 一.原型
? 原型的出現(xiàn),就是為了解決 構(gòu)造函數(shù)的缺點(diǎn)
? 也就是給我們提供了一個(gè)給對(duì)象添加方法的機(jī)會(huì)
? 不然構(gòu)造函數(shù)只能給對(duì)象添加屬性,不能合理的添加方法就太 LOW 了
? 1.原型的概念
? 每一個(gè)函數(shù)天生自帶一個(gè)成員(屬性和方法),叫做 prototype,是一個(gè)對(duì)象空間
? 即然每一個(gè)函數(shù)都有,構(gòu)造函數(shù)也是函數(shù),構(gòu)造函數(shù)也有這個(gè)對(duì)象空間
? 這個(gè) prototype 對(duì)象空間可以由函數(shù)名來訪問
? 即然prototype是個(gè)對(duì)象,那么我們就可以向prototype里面放入一些東西
? 注意:prototype里面可以放入屬性和方法,但是都是公有的,而且prototype里面的this也是指向new出來的實(shí)例對(duì)象
? function Person(name, age) {
? ? // 私有的屬性
? ? this.name = name;
? ? this.age = age;
? this.show = function () {//注意:如果方法構(gòu)造函數(shù)和原型上面都有,構(gòu)造函數(shù)里面的優(yōu)先
? ? return '我是構(gòu)造函數(shù)里面的'
? }
? }
? 給原型添加方法(公有的)
? Person.prototype.show = function () {
? ? return `我的名字叫${this.name},我今年${this.age}歲`;
? }
? Person.prototype.show1 = function () {
? ? return `我的名字叫${this.name},我今年${this.age}歲`;
? }
? Person.prototype.show2 = function () {
? ? return `我的名字叫${this.name},我今年${this.age}歲`;
? }
? // Person.prototype.sex = '男';
? let p1 = new Person('zhangsan', 20);
? let p2 = new Person('lisi', 30);
? console.log(p1.name);//zhangsan
? console.log(p1.age);//20
? console.log(p1.sex);//男,屬性是來自原型上面的
? console.log(p1.show());//我的名字叫zhangsan,我今年20歲
? console.log(p1.show === p2.show);//true
? Array.prototype.push = function () { };//覆蓋系統(tǒng)的push方法
? let a1 = [1, 2, 3];
? a1.push(4, 5, 6);
? console.log(a1);
? 二.總結(jié)面向?qū)ο箝_發(fā) - 混合開發(fā)
? 1.構(gòu)造函數(shù) + 原型
? 屬性放到構(gòu)造函數(shù)里面,合理的
? 方法放到原型上面,也是合理的
? 2.無論是構(gòu)造函數(shù)還是原型,里面的this指向是一樣的,都指向?qū)嵗龑?duì)象(new 出來的對(duì)象)
? 3.簡(jiǎn)單的邏輯,面向過程合理,復(fù)雜的邏輯,面向?qū)ο?/p>
? 三.面向過程改面向?qū)ο蟮囊?guī)則
? 1.變量或者常量 -> 變成屬性
? 2.函數(shù) -> 變成方法
? 3.注意this的指向 -> 箭頭函數(shù)
? 3.1.定時(shí)器->window
? 3.2.事件處理函數(shù)->事件源(觸發(fā)事件的元素對(duì)象)
? 3.3.無論是構(gòu)造函數(shù)還是原型,里面的this指向是一樣的,都指向?qū)嵗龑?duì)象
?
?
? let a1= new Array()
? let arr1 = [1, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5];
? let arr2 = [10, 20, 30, 30, 30, 30, 30, 30, 30, 40, 40, 40, 40, 40, 50];
? // console.log(arr);
? console.log(Object.prototype.toString.call(arr1))
? console.log(arr1.constructor)
? console.log(a1.constructor)
? console.log(Object.prototype.toString.call(a1))