问老师几个问题

来源:2-2 ES6中的类

学习plus

2021-02-06 17:27:54

相关截图:

http://img.mukewang.com/climg/601e5f9a09980f3c05990945.jpg

问题描述:

图中,实例方法和构造函数内的红框,执行哪一个都有speed+1的作用,都可以使用吗?

还是说规定属性写在实例方法内,方法写在构造函数内?!这个比较疑惑


问个题外问题,如果需要为一个实例添加自定义的方法需要类似上图黄框那样传入函数?

还是说直接 实例【方法名】 = 方法    //   ==》》   这样感觉如果自定义方法写多了,到时候自己都懵圈了,忘记有没有写,感觉应该有更好的方法 。


相关代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
class Car{

constructor(whell, color, length, width, speed, arrFunction){
this.whell = whell;
this.color = color;
this.length = length;
this.width = width;
this.speed = speed;
this.speedUp2 = function(){
this.speed += 1;
};
for(let {fName, fc} of arrFunction){
this[fName] = typeof fc == 'function' ? fc : {};
}

}
speedUp() {
this.speed += 1;
}
}
const car = new Car(3, 'blue', 20, 40, 10,[{
fName: 'fly',
fc(){
console.log('我飞起来了');
}
},{
fName: 'swim',
fc(){
console.log('我还能游泳');
}
}])
console.log(car.speed); // =>输出10
car.speedUp(); // =>执行speed+1
console.log(car.speed); // =>输出11

car.speedUp2(); // =>执行speed+1
console.log(car.speed); // =>输出12

console.log(car)
car.fly();
car.swim();
</script>
</body>
</html>


写回答

1回答

好帮手慕慕子

2021-02-06

同学你好,对于你的问题解答如下:

1、从控制台输出的实例对象car可知,speedUp2是添加到实例对象上的方法,而speedUp是添加在Car的原型对象上的方法,如下图所示:

http://img.mukewang.com/climg/601e67b8093b967c08070384.jpg

http://img.mukewang.com/climg/601e681109c9d55805290371.jpg

可以测试下,结合注释理解,示例:

http://img.mukewang.com/climg/601e68cb09aa7c6d07240290.jpg

http://img.mukewang.com/climg/601e68dd0985e89c05890300.jpg

由上面的分析可知,在constructor中书写的方法是添加到实例对象上的,在constructor外书写的方法是添加到类的原型对象上的,所以如果是每个实例对象共有的方法,那么可以推荐写在constructor外,如果每个实例特有的方法,推荐写在constructor内

2、如果是考虑给每一个实例化对象,在实例化的时候添加一个自定义的方法,推荐同学使用黄色框圈起来的这种方式。

如果是只为当前实例化对象添加一个方法,那么可以直接使用 实例【方法名】 = 方法  ,示例:

http://img.mukewang.com/climg/601e6bba0903816a03900158.jpg

祝学习愉快~

0

0 学习 · 10739 问题

查看课程

相似问题