日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

ES5-11原型与原型链深入、对象继承

發布時間:2023/12/10 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ES5-11原型与原型链深入、对象继承 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

原型

  • 誰調用,this就指向誰,當實例對象有該屬性時,不會去原型上查找

  • 創建對象的兩種方法:字面量、new Object()一般不用后面的
  • 二者創建出來的對象沒有差異

Object.create()

  • var 實例 = Object.create(對象/null)
  • 將對象或null作為實例的原型
  • new構造函數的時候做了什么
  • 實例化對象
  • 調用構造函數的初始化屬性和方法
  • 指定實例對象的原型
  • 將null作為實例的原型,原型中將不包含任何屬性!
  • 因此,不是所有對象都繼承Object.prototype
  • 無法查找到toString方法(沒有__proto__)
  • 手動增加的__proto__和自身的不一樣,沒有可以向上查找的原型鏈
var obj = Object.create(null) obj.num = 1; var obj1 = {count: 2 } obj.__proto__ = obj1; console.log(obj.count) // undefined obj.toString() // 報錯
  • document.write接收字符串,當傳入非String類型時,會先調用相應的toString方法

  • 原始值是沒有屬性的,基本包裝類有屬性和方法(有toString)

  • 除了undefined、null,其他的基本數據類型(Number、String、Boolean)都有自己的toSting方法

  • 基本數據類型的toSting方法和Object.prototype的toSting方法不同

原型鏈

  • 原型鏈的終點是Object.prototype

對象繼承

  • 將父級的實例作為我的原型對象
function GrandFather() {this.name = '祖先' } var grandFatherObj = new GrandFather() // 將父級的實例作為我的原型對象function Father() {this.name = '父親' } Father.prototype = grandFatherObj var fatherObj = new Father() function Child() {this.name = '孩子' } Child.prototype = fatherObj var childObj = new Child() console.log('祖先實例', grandFatherObj) console.log('父親實例', fatherObj) console.log('孩子實例', childObj)
  • 祖先的實例中的__proto__指向祖先的原型對象,構造器指向構造函數GrandFather
  • 祖先原型對象里也有__proto__指向Object.prototype,構造器指Object構造函數
  • Object.prototype有toString方法
  • 孩子實例修改父親的引用數據類型的屬性
  • 孩子實例不能修改父親的基本數據類型的屬性
  • 對于++操作符 相當于student.students = 1 + student.students(先讀取再賦值),會在孩子實例上創建這個屬性

調用方法時改變函數內this指向

call\apply\bind
方法.call(this指向的對象,參數…)
方法.apply(this指向的對象,arguments)

  • 插件計算器 方法寫在prototype里更合適
; (function () {function Compute() {this.plus = function (a, b) {return a + b}this.minus = function (a, b) {return a - b}}function FullCompute() {Compute.call(this)this.multi = function (a, b) {return a * b}this.divide = function (a, b) {return a / b}}window.FullCompute = FullCompute })() var myFullCompute = new FullCompute() console.log('加', myFullCompute.plus(8, 2)) // 10 console.log('減', myFullCompute.minus(8, 2)) // 6 console.log('乘', myFullCompute.multi(8, 2)) // 16 console.log('除', myFullCompute.divide(8, 2)) // 4 function Car(brand, color) {this.brand = brandthis.color = color } function Person(name, age) {this.name = namethis.age = agethis.printFn = function () {Car.call(this, 'Bentley', '黑')console.log(this.name + this.age + '歲的生日禮物是一輛' + this.color + '色的' + this.brand)} } var me = new Person('Stephy', 20) me.printFn() console.log('me', me)

總結

以上是生活随笔為你收集整理的ES5-11原型与原型链深入、对象继承的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。