JavaScript中的對象導論
面向對象編程(OOP)是一種編碼方法,它將代碼封裝為對象,并通過這些對象之間的交互來完成操作。JavaScript是一種靈活多變,非常適合實現OOP的編程語言。
問題1. 如何創建對象?
//通過對象字面量創建對象 let obj = { name: 'Alex', age: 24, gender: 'Male' }; //通過構造函數創建對象 function Person(name, age, gender) { this.name = name; this.age = age; this.gender = gender; } let person = new Person('Alex', 24, 'Male'); //通過Object.create()方法創建對象 let obj1 = Object.create(null); //創建一個空對象 let obj2 = Object.create(obj); //繼承obj的屬性和方法的對象
問題2. 如何使用prototype繼承?
prototype是JavaScript中用于實現繼承的機制。它可以在子對象中訪問父對象中的屬性和方法。
function Person(name, age, gender) { this.name = name; this.age = age; this.gender = gender; } Person.prototype.sayHello = function() { console.log('Hello, my name is ' + this.name); } function Student(name, age, gender, major) { Person.call(this, name, age, gender); this.major = major; } Student.prototype = Object.create(Person.prototype); Student.prototype.constructor = Student; let student = new Student('Alex', 24, 'Male', 'Computer Science'); student.sayHello();
問題3. 什么是封裝?
封裝是一種保護對象屬性和方法不被外部訪問的方法。在JavaScript中使用閉包實現封裝。
function Person(name, age, gender) { let _name = name; let _age = age; let _gender = gender; this.getName = function() { return _name; }; this.getAge = function() { return _age; }; this.getGender = function() { return _gender; }; this.setName = function(name) { _name = name; }; this.setAge = function(age) { _age = age; }; this.setGender = function(gender) { _gender = gender; }; }
問題4. 如何使用繼承的“多態”特性
多態是面向對象編程中,子類可以覆蓋父類的方法,并賦予不同的實現方式,以達到更靈活的編程目的。
function Person() {} Person.prototype.sayHello = function() { console.log('Hello, I am a Person'); } function Student() {} Student.prototype = Object.create(Person.prototype); Student.prototype.constructor = Student; Student.prototype.sayHello = function() { console.log('Hello, I am a Student'); } function Teacher() {} Teacher.prototype = Object.create(Person.prototype); Teacher.prototype.constructor = Teacher; Teacher.prototype.sayHello = function() { console.log('Hello, I am a Teacher'); } let person = new Person(); let student = new Student(); let teacher = new Teacher(); person.sayHello(); student.sayHello(); teacher.sayHello();
以上就是JavaScript中面向對象編程的常見問題,希望能夠對你的編程有所啟發。
下一篇div下標值