>  기사  >  웹 프론트엔드  >  객체 지향 JavaScript에 대한 첫 소개

객체 지향 JavaScript에 대한 첫 소개

巴扎黑
巴扎黑원래의
2017-09-04 09:46:231021검색

js 객체지향 지식은 가장 기초적인 입문 지식 포인트입니다. 아래는 이 글의 예제 코드를 통해 js 객체지향 지식을 자세히 소개한 것입니다. 관심 있는 친구들은 함께 배울 수 있습니다

수업 선언

1. 생성 기능


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

2.ES6 클래스


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

클래스 상속

1. 생성자

원리: 이것이 를 가리키는 경우 하위 클래스 연산을 변경하지만 상위 클래스의 프로토타입 체인에 있는 속성은 상속되지 않습니다. 이는 불완전 상속입니다


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. 생성자 + 프로토타입 체인

Best Practice


// 父类
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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