老师帮忙看下是否正确

来源: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定义的,它是实例自身的方法:

https://img.mukewang.com/climg/619f35090904081e05870197.jpg

在class中,应该写在constructor中,如下:

https://img.mukewang.com/climg/619f35580924680c06620415.jpg

2、run方法是在构造函数原型对象上定义的,它属于实例的方法:

https://img.mukewang.com/climg/619f358109bcc1ef06380123.jpg

在class中,它应该写在constructor外面。

由于static关键字,代表“静态”,即“类自身的东西”,所以不能用static修饰run方法:

https://img.mukewang.com/climg/619f36240956bae809020547.jpg

3、show方法、intro属性,是直接定义在构造函数Person上面的,它们属于“类自身的东西”:

https://img.mukewang.com/climg/619f367f090880c306040349.jpg

因此都要使用static关键字修饰:

https://img.mukewang.com/climg/619f37210901af1e06470146.jpg

最终代码如下:

https://img.mukewang.com/climg/619f37080999654906650503.jpg

祝学习愉快!

0

0 学习 · 17877 问题

查看课程