老师帮忙看下是否正确
来源:3-3 编程练习
L_Tomato
2021-11-25 14:48:47
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <script> /* function Person(name, age) { this.name = name; this.age = age; this.say = function() { console.log(this.name, this.age) } } Person.prototype.run = function() { console.log("run") } Person.intro = "this is a Person class" Person.show = function() { console.log('show') } */ class Person{ constructor(name,age){ this.name= name; this.age= age; } say(){ console.log(this.name, this.age) } static run(){ console.log("run") } static intor = 'this is a Person class' show(){ console.log('show') } } console.log(Person.intor); const p = new Person('abc',18); p.say(); p.show(); </script></body></html>
1回答
好帮手慕久久
2021-11-25
同学你好,代码有如下问题:
1、say方法是在构造函数中使用this定义的,它是实例自身的方法:
在class中,应该写在constructor中,如下:
2、run方法是在构造函数原型对象上定义的,它属于实例的方法:
在class中,它应该写在constructor外面。
由于static关键字,代表“静态”,即“类自身的东西”,所以不能用static修饰run方法:
3、show方法、intro属性,是直接定义在构造函数Person上面的,它们属于“类自身的东西”:
因此都要使用static关键字修饰:
最终代码如下:
祝学习愉快!
相似问题