学习 React 之前先了解一下 JS 中的类
什么是类?
大家好...👋
这篇文章将简要介绍 JavaScript 中面向对象编程的概念,例如类和对象。欢迎阅读本系列的往期文章。也欢迎在💬里给我推荐一些新的主题。
什么是类?
类是一种独立的小程序,它拥有自己的上下文——方法(函数)和属性(变量) 。类的不同实例 (称为对象)可以创建并作为变量处理。
创建 JavaScript 类
class Author {
constructor(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
getName() {
return `${this.firstname} ${this.lastname}`;
}
}
//A new object can be created with the new keyword and
var me = new Author('Rajshree', 'vats');
//the ‘constructor’ of the class can be called at the same time
console.log(me.getName());
各种类方法(例如)getName()
可用于读取或写入properties
的object
。该console.log()
方法将打印作为参数传递给它的任何内容。
JavaScript 中的对象创建
JavaScript 对象是命名值的容器,这些值被称为属性和方法。对象也是变量。但是对象可以包含许多值。
在这里,我们定义了两个对象student1
和students2
。
-
JavaScript 对象中的命名值称为
属性。const student1 = { //common practice is to use `const` Name:"Rajshree", Roll : '800', Cgpa : '8.5' };
-
对象方法是包含函数
定义的对象属性。let student2 = { Name:"Rajshree", Roll : '800', Cgpa : '8.5', printScore() { console.log(this.Cgpa) } }
关键词this
this 的值取决于它使用的上下文。因此,如果它在函数中被使用,它的值将取决于该函数的调用方式。赋值
方式如下:this
- 隐式绑定:使用点符号调用函数。👇
getName() {
return `${this.firstname} ${this.lastname}`;
}
- 显式绑定:函数是对象的一部分。👇
var printName = function() {
console.log(`My name is ${this.firstname} ${this.lastname}`);
};
var me = new Author('Rajshree', 'vats');
printName.call(me);
.call()
可用于将函数明确绑定到对象并将.apply()
所有参数传递到一个数组中。
bind()
:.bind()
设置一个 this 上下文并返回一个绑定 this 上下文的新函数。
var printName = function() {
console.log(`My name is ${this.firstname} ${this.lastname}`);
};
var me = new Author('Rajshree', 'vats');
// Here we bind the me object to the printName() and get a new function newPrintName()
const newPrintName = printName.bind(me);
-
全局上下文:当在任何上下文(例如、或)
this
之外使用时,它指的是全局对象。class
function
object
-
箭头函数 和
this
:JavaScript 中的apply()
、 和等方法在箭头函数中bind()
对 没有任何影响。 的值与函数调用时的值保持不变。this
this
作品
在编程中,对象组合指的是类中包含其他类的实例作为属性,以实现所需的功能,而不是继承类。React 和 JavaScript 中实现对象组合的方式比较先进。
遗产
继承使新类能够继承现有类的属性和方法。被其他类继承的类称为超类或基类。从超类继承的类称为子类或派生类。
然而,与类组合相比,继承有一定的局限性。组合使代码变得动态且适应变化,同时也引入了更少的错误。
今天就到这里啦!!!
希望你喜欢。如果你对此有任何疑问,或者有什么建议,可以在推特上联系我😊。
文章来源:https://dev.to/rajsreevats/classes-in-js-before-learning-react-1kil