>  기사  >  웹 프론트엔드  >  js 객체지향에 대한 깊은 이해

js 객체지향에 대한 깊은 이해

php中世界最好的语言
php中世界最好的语言원래의
2018-04-18 11:04:191219검색

이번에는 js객체지향에 대한 심층적인 이해를 가져왔습니다. js 객체지향에 대한 심층적인 이해를 위한 노트는 무엇인가요?

수업 선언

1. 생성자

function Animal() {
 this.name = 'name'
}
// 实例化
new Animal()

2.ES6 수업

class Animal {
 constructor() {
  this.name = 'name'
 }
}
// 实例化
new Animal()

클래스 상속

1. 생성자의 도움으로 상속 구현

원리: 런타임 중에 하위 클래스의 this 포인터를 변경하지만 상위 클래스의 프로토타입 체인에 있는

attributes는 상속되지 않습니다. 이는 불완전한 상속

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())
이 기사의 사례를 읽으신 후 방법을 마스터하셨다고 생각합니다. 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트의 다른 관련 기사를 주목하세요!

추천 도서:



위 내용은 js 객체지향에 대한 깊은 이해의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.