首頁 > web前端 > js教程 > 主體

JavaScript 面向對像初識

巴扎黑
發布: 2017-09-04 09:46:23
原創
1020 人瀏覽過

js 物件導向知識是最基礎的入門知識點,以下透過本文實例程式碼給大家詳細介紹js 物件導向的知識,有興趣的朋友一起學習吧

類的宣告

1. 建構子


#
function Animal() {
 this.name = 'name'
}
// 实例化
new Animal()
登入後複製

2.ES6 class


#
class Animal {
 constructor() {
  this.name = 'name'
 }
}
// 实例化
new Animal()
登入後複製

類別的繼承

1. 借助建構子實作繼承

原理:改變子類別運行時的this 指向,但是父類別原型鏈上的屬性並沒有被繼承,是不完全的繼承


function Parent() {
 this.name = 'Parent'
}
Parent.prototype.say = function(){
 console.log('hello')
}
function Child() {
 Parent.call(this)
 this.type = 'Child'
}
console.log(new Parent())
console.log(new Child())
登入後複製

2. 借助原型鏈實現繼承

原理:原型鏈,但是在一個子類別實例中改變了父類別中的屬性,其他實例中的該屬性也會改變子,也是不完全的繼承


function Parent() {
 this.name = 'Parent'
 this.arr = [1, 2, 3]
}
Parent.prototype.say = function(){
 console.log('hello')
}
function Child() {
 this.type = 'Child'
}
Child.prototype = new Parent()
let s1 = new Child()
let s2 = new Child()
s1.arr.push(4)
console.log(s1.arr, s2.arr)
console.log(new Parent())
console.log(new Child())
console.log(new Child().say())
登入後複製

3. 建構子+ 原型鏈

最佳實踐


// 父类
function Parent() {
 this.name = 'Parent'
 this.arr = [1, 2, 3]
}
Parent.prototype.say = function(){
 console.log('hello')
}
// 子类
function Child() {
 Parent.call(this)
 this.type = 'Child'
}
// 避免父级的构造函数执行两次,共用一个 constructor
// 但是无法区分实例属于哪个构造函数
// Child.prototype = Parent.prototype
// 改进:创建一个中间对象,再修改子类的 constructor
Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child
// 实例化
let s1 = new Child()
let s2 = new Child()
let s3 = new Parent()
s1.arr.push(4)
console.log(s1.arr, s2.arr) // [1, 2, 3, 4] [1, 2, 3]
console.log(s2.constructor) // Child
console.log(s3.constructor) // Parent
console.log(new Parent())
console.log(new Child())
console.log(new Child().say())
登入後複製

以上是JavaScript 面向對像初識的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!