JavaScript 中的面向对象编程简介
由于 JavaScript 在 Web 开发中被广泛使用,在本文中,我们将探索JavaScript支持的一些面向对象机制,以充分利用它。 OOPS 上 JavaScript 中的一些常见面试问题包括:“如何在 JavaScript 中实现面向对象编程?它们与其他语言有何不同?你能在 JavaScript 中实现继承吗……”
有一些特性或机制使语言面向对象,例如:
- 目的
- 课程
- 封装
- 遗产
让我们深入了解其中的每一个细节,看看它们是如何在 JavaScript 中实现的。
1. 对象——对象是包含属性和方法的唯一实体。例如,“汽车”是一个现实生活中的对象,它具有颜色、类型、型号、马力等一些特征,并执行某些动作,如驱动。在面向对象的编程中,对象的特征称为属性,而动作称为方法。对象是类的一个实例。对象在 JavaScript 中无处不在,几乎每个元素都是对象,无论是函数、数组还是字符串。
注意: javascript 中的 Method 是对象的属性,其值为函数。
在 JavaScript 中可以通过两种方式创建对象:
- 使用对象字面量
Javascript
//Defining object
let person = {
first_name:'Mukul',
last_name: 'Latiyan',
//method
getFunction : function(){
return (`The name of the person is
${person.first_name} ${person.last_name}`)
},
//object within object
phone_number : {
mobile:'12345',
landline:'6789'
}
}
console.log(person.getFunction());
console.log(person.phone_number.landline);
Javascript
//using a constructor
function person(first_name,last_name){
this.first_name = first_name;
this.last_name = last_name;
}
//creating new instances of person object
let person1 = new person('Mukul','Latiyan');
let person2 = new person('Rahul','Avasthi');
console.log(person1.first_name);
console.log(`${person2.first_name} ${person2.last_name}`);
Javascript
// Object.create() example a
// simple object with some properties
const coder = {
isStudying : false,
printIntroduction : function(){
console.log(`My name is ${this.name}. Am I
studying?: ${this.isStudying}.`)
}
}
// Object.create() method
const me = Object.create(coder);
// "name" is a property set on "me", but not on "coder"
me.name = 'Mukul';
// Inherited properties can be overwritten
me.isStudying = true;
me.printIntroduction();
Javascript
// Defining class using es6
class Vehicle {
constructor(name, maker, engine) {
this.name = name;
this.maker = maker;
this.engine = engine;
}
getDetails(){
return (`The name of the bike is ${this.name}.`)
}
}
// Making object with the help of the constructor
let bike1 = new Vehicle('Hayabusa', 'Suzuki', '1340cc');
let bike2 = new Vehicle('Ninja', 'Kawasaki', '998cc');
console.log(bike1.name); // Hayabusa
console.log(bike2.maker); // Kawasaki
console.log(bike1.getDetails());
Javascript
// Defining class in a Traditional Way.
function Vehicle(name,maker,engine){
this.name = name,
this.maker = maker,
this.engine = engine
};
Vehicle.prototype.getDetails = function(){
console.log('The name of the bike is '+ this.name);
}
let bike1 = new Vehicle('Hayabusa','Suzuki','1340cc');
let bike2 = new Vehicle('Ninja','Kawasaki','998cc');
console.log(bike1.name);
console.log(bike2.maker);
console.log(bike1.getDetails());
Javascript
//encapsulation example
class person{
constructor(name,id){
this.name = name;
this.id = id;
}
add_Address(add){
this.add = add;
}
getDetails(){
console.log(`Name is ${this.name},Address is: ${this.add}`);
}
}
let person1 = new person('Mukul',21);
person1.add_Address('Delhi');
person1.getDetails();
Javascript
// Abstraction example
function person(fname,lname){
let firstname = fname;
let lastname = lname;
let getDetails_noaccess = function(){
return (`First name is: ${firstname} Last
name is: ${lastname}`);
}
this.getDetails_access = function(){
return (`First name is: ${firstname}, Last
name is: ${lastname}`);
}
}
let person1 = new person('Mukul','Latiyan');
console.log(person1.firstname);
console.log(person1.getDetails_noaccess);
console.log(person1.getDetails_access());
Javascript
//Inheritance example
class person{
constructor(name){
this.name = name;
}
//method to return the string
toString(){
return (`Name of person: ${this.name}`);
}
}
class student extends person{
constructor(name,id){
//super keyword to for calling above class constructor
super(name);
this.id = id;
}
toString(){
return (`${super.toString()},Student ID: ${this.id}`);
}
}
let student1 = new student('Mukul',22);
console.log(student1.toString());
输出:
- 使用对象构造函数:
Javascript
//using a constructor
function person(first_name,last_name){
this.first_name = first_name;
this.last_name = last_name;
}
//creating new instances of person object
let person1 = new person('Mukul','Latiyan');
let person2 = new person('Rahul','Avasthi');
console.log(person1.first_name);
console.log(`${person2.first_name} ${person2.last_name}`);
输出:
- 使用Object.create() 方法: Object.create() 方法创建一个新对象,使用现有对象作为新创建对象的原型。
Javascript
// Object.create() example a
// simple object with some properties
const coder = {
isStudying : false,
printIntroduction : function(){
console.log(`My name is ${this.name}. Am I
studying?: ${this.isStudying}.`)
}
}
// Object.create() method
const me = Object.create(coder);
// "name" is a property set on "me", but not on "coder"
me.name = 'Mukul';
// Inherited properties can be overwritten
me.isStudying = true;
me.printIntroduction();
输出:
2. 类——类是对象的蓝图。一个类可以有许多对象,因为类是一个模板,而对象是类的实例或具体实现。
在我们进一步实现之前,我们应该知道与其他面向对象语言不同,JavaScript 中没有类,我们只有 Object。更准确地说,JavaScript 是一种基于原型的面向对象语言,这意味着它没有类,而是使用构造函数定义行为,然后使用原型重用它。
注意:即使是 ECMA2015 提供的类也是对象。
JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.
–Mozilla Developer Network
例子:
让我们使用 ES6 类,然后我们将研究定义 Object 的传统方式并将它们模拟为类。
Javascript
// Defining class using es6
class Vehicle {
constructor(name, maker, engine) {
this.name = name;
this.maker = maker;
this.engine = engine;
}
getDetails(){
return (`The name of the bike is ${this.name}.`)
}
}
// Making object with the help of the constructor
let bike1 = new Vehicle('Hayabusa', 'Suzuki', '1340cc');
let bike2 = new Vehicle('Ninja', 'Kawasaki', '998cc');
console.log(bike1.name); // Hayabusa
console.log(bike2.maker); // Kawasaki
console.log(bike1.getDetails());
输出:
传统方式。
Javascript
// Defining class in a Traditional Way.
function Vehicle(name,maker,engine){
this.name = name,
this.maker = maker,
this.engine = engine
};
Vehicle.prototype.getDetails = function(){
console.log('The name of the bike is '+ this.name);
}
let bike1 = new Vehicle('Hayabusa','Suzuki','1340cc');
let bike2 = new Vehicle('Ninja','Kawasaki','998cc');
console.log(bike1.name);
console.log(bike2.maker);
console.log(bike1.getDetails());
输出:
如上例所示,在 ES6 中定义和重用对象要简单得多。因此,我们将在所有示例中使用 ES6。
3. 封装——将属性和函数封装在一个单元内的过程称为封装。
让我们通过一个例子来理解封装。
Javascript
//encapsulation example
class person{
constructor(name,id){
this.name = name;
this.id = id;
}
add_Address(add){
this.add = add;
}
getDetails(){
console.log(`Name is ${this.name},Address is: ${this.add}`);
}
}
let person1 = new person('Mukul',21);
person1.add_Address('Delhi');
person1.getDetails();
输出:
在上面的示例中,我们只是使用构造函数创建了一个人对象,并初始化它的属性并使用它的功能,我们不关心实现细节。我们正在使用 Objects 接口而不考虑实现细节。
有时封装是指隐藏数据或数据抽象,这意味着表示隐藏背景细节的基本特征。大多数 OOP 语言都提供了访问修饰符来限制变量的范围,但它们在 JavaScript 中没有这样的访问修饰符,但它们是我们可以限制类/对象内变量范围的某种方式。
例子:
Javascript
// Abstraction example
function person(fname,lname){
let firstname = fname;
let lastname = lname;
let getDetails_noaccess = function(){
return (`First name is: ${firstname} Last
name is: ${lastname}`);
}
this.getDetails_access = function(){
return (`First name is: ${firstname}, Last
name is: ${lastname}`);
}
}
let person1 = new person('Mukul','Latiyan');
console.log(person1.firstname);
console.log(person1.getDetails_noaccess);
console.log(person1.getDetails_access());
输出:
在上面的示例中,我们尝试访问一些属性( person1.firstname )和函数( person1.getDetails_noaccess ),但它返回undefine而它们是我们可以从person对象( person1.getDetails_access() )访问的方法,通过更改定义一个函数的方式,我们可以限制它的范围。
4. 继承——一个对象的某些属性和方法被另一个对象使用的概念。与类继承类的大多数 OOP 语言不同,JavaScript 对象继承对象,即一个对象的某些特性(属性和方法)可以被其他对象重用。
让我们通过示例来理解继承:
Javascript
//Inheritance example
class person{
constructor(name){
this.name = name;
}
//method to return the string
toString(){
return (`Name of person: ${this.name}`);
}
}
class student extends person{
constructor(name,id){
//super keyword to for calling above class constructor
super(name);
this.id = id;
}
toString(){
return (`${super.toString()},Student ID: ${this.id}`);
}
}
let student1 = new student('Mukul',22);
console.log(student1.toString());
输出:
在上面的例子中,我们定义了一个具有某些属性和方法的Person对象,然后我们继承了Student对象中的Person对象,并使用了 person 对象的所有属性和方法,并为Student定义了某些属性和方法。
注意: Person 和 Student 对象都有相同的方法,即 toString(),这被称为Method Overriding 。方法覆盖允许子类中的方法具有与父类相同的名称和方法签名。
在上面的代码中,super 关键字用于引用直接父类实例变量。
JavaScript 以网页开发而闻名,但它也用于各种非浏览器环境。您可以按照这个 JavaScript 教程和 JavaScript 示例从头开始学习 JavaScript。