>  기사  >  웹 프론트엔드  >  JS는 객체 지향 프로그래밍을 어떻게 구현합니까? js 객체지향 프로그래밍의 원리 소개

JS는 객체 지향 프로그래밍을 어떻게 구현합니까? js 객체지향 프로그래밍의 원리 소개

不言
不言원래의
2018-08-18 16:53:143519검색

이 기사의 내용은 JS가 객체지향 프로그래밍을 구현하는 방법에 관한 것입니다. js 객체지향 프로그래밍의 원리에 대한 소개는 특정한 참고 가치가 있습니다. 도움이 필요한 친구들이 참고할 수 있기를 바랍니다.

1. 객체 지향 프로그래밍이란 무엇인가요? 🎜#

2. 객체 지향 프로그래밍의 목적은
대규모 소프트웨어 프로젝트에서 널리 사용됩니다.

3. 객체지향 프로그래밍의 장점(상속, 다형성, 캡슐화)
상속: 상위 클래스의 모든 데이터와 기능을 가져오고 복사를 수행합니다.

다형성: 동일한 메소드 이름이라도 해당 메소드를 구현하는 객체에 따라 동작이 다릅니다.

캡슐화: 객체 데이터와 기능을 집계하고 외부 세계와의 접촉을 제한합니다(액세스 권한).

JS에서 객체지향 프로그래밍을 구현하는 방법(참조)
1. 프로토타입 체인 상속

function Person() {
    this.name = 'per'
    this.obj = {
        name: ''
    }
}
Person.prototype.getName = function() {
    return this.obj.name
}
Person.prototype.setName = function(name) {
    this.name = name
    // 引用类型的赋值会同步给所有子类
    this.obj.name = name
}
function Student() {
    
}
Student.prototype = new Person()

const stu1 = new Student()
const stu2 = new Student()

stu1.setName('stu')
stu1.getName()
stu2.getName()

단점: 참조 유형이 수정되는 경우 , 모든 하위 클래스에 동기화됩니다

2. 생성자 상속
function Person() {
    this.obj = {
        name: 'a'
    }
    this.setName = name => {
        this.obj.name = name
    }
    this.getName = () => {
        return this.obj.name
    }
}
function Student() {
    Person.call(this)
}
const stu1 = new Student()
const stu2 = new Student()
stu1.setName('stu')
stu1.getName()
stu2.getName()
단점: 상위 클래스의 기능은 하위 클래스에서 공유되지 않으며 이는 동적으로 복사하는 것과 같습니다. 코드 복사본

3. 결합 상속
function Person() {
    this.obj = {
        name: 'a'
    }
}
Person.prototype.getName = function() {
    return this.obj.name
}
Person.prototype.setName = function(name) {
    this.name = name
    // 引用类型的赋值会同步给所有子类
    this.obj.name = name
}
function Student() {
    // 继承属性
    Person.call(this)
}
// 继承方法
Student.prototype = new Person()
단점: 상위 클래스의 속성 복사가 두 번 수행됩니다

4. #🎜🎜 #
function Person() {
    this.obj = {
        name: 'a'
    }
}
Person.prototype.getName = function() {
    return this.obj.name
}
Person.prototype.setName = function(name) {
    this.name = name
    // 引用类型的赋值会同步给所有子类
    this.obj.name = name
}
function Student() {
    // 继承属性
    Person.call(this)
}
// 这里实现方法的继承
function inherit(sub, parent) {
    sub.prototype = Object.create(parent.prototype)
    sub.prototype.constructor = sub       
}
inherit(Student, Person)
이것은 결합 상속의 상위 클래스 코드의 2차 실행 문제를 해결합니다

5 클래스 구현 상속(참조)

class Person {
    constructor(){
        this.obj = {
            name: 'a'
        }
    }
    get name() {
        return this.obj.name
    }
    set name(name) {
        this.obj.name = name
    }
}
class Student extends Person {
    constructor() {
        super()
    }
}
관련 권장사항: #🎜 🎜#

js 객체 지향 객체를 생성하는 다양한 방법에 대한 요약_js 객체 지향


#🎜 🎜#javascript 객체 지향 프로그래밍 code_js 객체 지향

위 내용은 JS는 객체 지향 프로그래밍을 어떻게 구현합니까? js 객체지향 프로그래밍의 원리 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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