首页 > 试题广场 >

执行以下程序,输出结果为() class Phone{ co

[单选题]

执行以下程序,输出结果为()

class Phone{
  constructor(price){
    this.price = price;
  }
  get price(){
    return 999;
  }
}
var p = new Phone(888);
console.log(p.price);

  • 999
  • undefined
  • 抛出异常
  • 888
这个应该是class底层用到了Objetct.defineProperty() :  对访问器属性price只是设置了get,set默认没有,所以price属性视为读属性
   然后在第三行  this.price = price又用了设置price(set),所以会报错: price是只读的
  解决: get price() {}后面加上: set price(value) {}          ===>   set需要参数!!!        就返回999了
发表于 2022-01-06 23:44:25 回复(4)
本题报错:
这个类只设置了get方法,没有设置set方法,那么默认price属性是只读的,那就不能在constructor里再设置 this.price = price



解决办法有两种:
        第一种:不要在constructor里设置 this.price = price
        第二种:给这个类添加一个set 方法






编辑于 2022-01-20 15:14:24 回复(2)
忘记看没定义了😡
发表于 2021-12-13 19:50:04 回复(0)
报错是: Uncaught TypeError: Cannot set property price of #<Phone> which has only a getter
    at new Phone (<anonymous>:5:28)
    at <anonymous>:17:9

这是getter和setter必须一起用的意思吗?
发表于 2021-12-13 21:04:08 回复(1)
是因为属性名和get函数名一样 
发表于 2022-01-03 10:26:44 回复(0)
这里我做错了,我的想法是这里因为没有设置 setter,所以对属性赋值会静默失败
但是我忘记了一个事实,class 类中自动启用 严格模式, 也就是说,对只读属性进行设置会抛出错误
发表于 2022-02-15 18:11:25 回复(0)
class Phone{
  constructor(price){
    this.price = price;
  }
  get price(){
    return 999;
  }
  set price(value){values}
}
var p = new Phone(888);
console.log(p.price);
这样就可以正常返回
编辑于 2022-02-14 15:56:21 回复(0)
get set 要一起使用~~~
发表于 2022-09-11 21:44:06 回复(0)
get和set必须同级出现
发表于 2022-04-19 10:16:16 回复(1)
没有定义参数吧
发表于 2021-12-14 16:49:33 回复(1)
加个setter,这样就不报错了
class Phone{
  constructor(price){
    this.price = price;
  }
  get price(){
    return 999;
  }
  set price(price){}
}
var p = new Phone(888);
console.log(p.price);

发表于 2022-10-01 19:45:40 回复(0)
get和set必须成对出现,如果有get/set则输出999,如果没有,则只输出888

发表于 2022-09-07 14:33:34 回复(0)
class内部默认采用严格模式,严格模式下,属性没有setter,赋值会报错
发表于 2022-06-09 17:19:27 回复(0)