根据这篇文章,它应该是一种Javascript 2.0方式来定义类.但是,我从未在实践中看到过这一点.这样的问题.如何使用class关键字和Javascript 1.x做事的方式有什么区别?
小智 52
我知道这是一个老帖子,但截至今天,即随着ECMAScript 6的出现,我们可以声明javascript类.
语法如下:
class Person{
constructor(name){
this.name = name;
}
printName(){
console.log('Name is '+this.name);
}
}
var john = new Person('John Doe');
john.printName(); // This prints 'Name is John Doe'
Run Code Online (Sandbox Code Playgroud)
这篇文章的完整指南可以在这篇文章中找到
Dav*_*ebb 46
您从未class在实践中看到关键字的原因是JavaScript的所有当前实现都是1.x.
JavaScript 2.0被合并到ECMAScript 4中,这是非常不受欢迎的,因此从未进入现实世界.
那么要回答你的问题,你如何使用class关键字?你不能.
在ES6该class关键字进行了介绍。该class关键字不超过上已经存在的原型继承格局的顶部语法糖。javascript中的类基本上是另一种编写构造函数的方法,可使用该构造函数来使用new关键字创建新对象。
class Person {
constructor(name) {
this.name = name;
}
talk() { console.log('hi'); }
}
const me = new Person('Willem');
console.log(typeof Person)
// logs function, Person class is just another constructor function under the hood
console.log(me.__proto__ === Person.prototype)
// logs true, classes just use the same prototypal inheritance pattern which is used by constructor functions.
// An object created with the new keyword gets a __proto__ property on it which is a reference to the prototype property on a constructor function.Run Code Online (Sandbox Code Playgroud)
在上面的示例中,可以在第一个日志中观察到,从class关键字创建的类实际上是底层函数。
console.log(typeof Person) // logs 'function'
Run Code Online (Sandbox Code Playgroud)
es6类使用与构造函数相同的原型继承模式。这是另一个示例来演示此行为:
console.log(typeof Person) // logs 'function'
Run Code Online (Sandbox Code Playgroud)
上例中的要点是,可以在运行时更改任何dog实例的树皮方法。这是因为使用Dog类创建的任何对象的树皮方法都只是引用此函数。
| 归档时间: |
|
| 查看次数: |
26498 次 |
| 最近记录: |