[CoffeeScript] Level 6: Object Orientation

Classes - Part I

Create a Coffee class that will produce coffee objects. In that class, create a constructor that takes name and level as arguments and sets them as instance variables. Also, make sure you create a function called isRussian.

class Coffee
  constructor : (@name='Russian', @level=2) ->
    @name = 'Russian'
    @level = 2
    
  isRussian: ->
    "#{@name} is Russian"

 

Classes - Part II

For an already existing Coffee class, create a new coffee object passing in your name (string) and any number (as the level), then assign it to a variable named coffee.

coffee = new Coffee('Zhentian Wan', 9)

 

Property Arguments

Refactor the constructor to use property arguments. Also, set @level to be an optional argument by setting its default value to 0.

class Coffee
  constructor: (@name, @level=0) ->

  isRussian: -> @name is 'Russian'

 

Class Inheritance

Make the Coffee class inherit from Drink and override the serve method to return false if@sleeve is false, otherwise invoke the superclass method. (Note: The Drink class is defined below).

class Drink
  sleeve: null
  serve: ->
    alert('Pouring drink')

Answer:

class Coffee extends Drink
  constructor: (@name, @level=0) ->

  serve: ->
    return false if @sleeve is not true
    super()

 

Classes with jQuery

On the DrinkLink class below, implement the watchClick method so that when any link is clicked, its color is changed to #F00.

class DrinkLink
  watchClick: -> 
    $('a').click (event) -> 
      event.preventDefault()
      $(@).css(color: '#F00')

 

Watch those @'s

Fix the bug on the code below, which is causing the @linkClicked variable to not be properly set when a link is clicked.

class DrinkLink
  constructor: (@linkClicked=false) ->
  watchClick: ->
    $('.drink a').click (event) ->
      $(event.target).css('color', '#F00')
      @linkClicked = true

Answer:

class DrinkLink
  constructor: (@linkClicked=false) ->
  watchClick: ->
    $('.drink a').click (event) =>
      $(event.target).css('color', '#F00')
      @linkClicked = true

 

posted @   Zhentiw  阅读(305)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示