Skip to content

Instantly share code, notes, and snippets.

@cnruby
Created June 19, 2011 22:44
Show Gist options
  • Save cnruby/1034862 to your computer and use it in GitHub Desktop.
Save cnruby/1034862 to your computer and use it in GitHub Desktop.
HOW TO USE PROTOTYPE for CofffeeScript
# 理解JavaScript的prototype属性
#
# 类Dog - 类名称
# 属性name - 类Dog的对象属性
# 类属性species - 类Dog的类属性
# 对象dog_a - 类Dog的对象
# 对象dog_b - 类Dog的对象
#
# 类属性species是prototype对象的属性;
# 类Dog.prototype是实例对象共享的对象;
# 只要修改了prototype对象属性,如类Dog.prototype.species,就会同时影响到实例对象属性,如对象dog_a.类属性species;
#
# 例如:
#
# $ coffee class_base_003.js.coffee
# # 对象dog_a.类属性species = 犬科
# # 对象dog_b.类属性species = 犬科
# # 对象dog_a.类属性species = 猫科
# # 对象dog_b.类属性species = 犬科
# # 对象dog_a.类属性species = 猫科
# # 对象dog_b.类属性species = 猫科
class 类Dog
constructor: (@属性name) ->
类属性species: '犬科'
对象dog_a = new 类Dog '大毛'
对象dog_b = new 类Dog '二毛'
console.log '对象dog_a.类属性species = ' + 对象dog_a.类属性species # 显示"犬科"
console.log '对象dog_b.类属性species = ' + 对象dog_b.类属性species # 显示"犬科"
对象dog_a.类属性species = '猫科'
console.log '对象dog_a.类属性species = ' + 对象dog_a.类属性species # 显示"猫科"
console.log '对象dog_b.类属性species = ' + 对象dog_b.类属性species # 显示"犬科",不受<对象dog_a>的影响
类Dog.prototype.类属性species = '猫科';
console.log '对象dog_a.类属性species = ' + 对象dog_a.类属性species # 显示"猫科"
console.log '对象dog_b.类属性species = ' + 对象dog_b.类属性species # 显示"猫科",受<类Dog..prototype>的影响
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment