方法类方法和原型之间有什么区别? [英] What are the differences between method class methods and prototype?
问题描述
请看下面的示例代码,请解释我在下面提到的问题!
see below the sample code and please explain my question below I mention!
class User{
constructor(email,name){
this.email = email;
this.name = name;
}
login(){
console.log(this.email);
}
}
var u1 = new User("dil@gm.com","dil");
u1.login();
function User(email,name){
this.email = email;
this.name = name;
}
User.prototype.login = function(){
console.log(this.email);
}
var u2 = new User("dil@gm.com","dil");
u2.login();
上面这两种编码有什么区别?当两个实例都访问这些方法时,我的意思是正常的方法声明和原型减速?
推荐答案
没什么.
JavaScript 最初没有类的概念,对于 JavaScript 中的 OOP,实现了基于原型的方法.
JavaScript didn't originally have the concept of a Class, for OOP in JavaScript, the prototype-based approach was implemented.
自从 ESX(记不太清楚)以来,引入了类的概念,本质上是将基于原型的语法包装成一种更流行的基于类的语法,开发人员通常习惯于在不同的语言中使用.
Since ESX (can't remember exactly), the concept of a Class was introduced, essentially wrapping the prototype-based syntax, into a more popular Class-based syntax that developers are usually used to using in different languages.
我鼓励使用新语法,因为它通常更具可读性,并且(至少对我而言)在 JavaScript 中处理对象时更有意义.
I'd encourage using the new syntax, as it's generally more readable and (for me at-least) makes more sense when working with objects in JavaScript.
JavaScript 在为我们带来 async/await 时实现了类似的概念,将旧的 Promise.resolve|.reject
包裹在一个同步感觉 API,JavaScript 充满了语法糖和 hacky 解决方法以提供类似的支持与其他语言一样.
JavaScript implemented a similar concept when bringing us async/await, wrapping the old Promise.resolve|.reject
with a synchronous feeling API, JavaScript is full of syntax sugar and hacky workarounds to provide similar support as other languages.
这篇关于方法类方法和原型之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!