javascript OOP 面向对象编程
Pseudo-class declaration
原文地址:http://javascript.info/tutorial/pseudo-classical-pattern#pseudo-class-declaration
A pseudo-class consists of the constructor function and methods.
For example, here’s the Animal
pseudo-class with single method sit
and two properties.
function Animal(name) { this.name = name } Animal.prototype = { canWalk: true, sit: function() { this.canWalk = false alert(this.name + ‘ sits down.‘) } } var animal = new Animal(‘Pet‘) // (1) alert(animal.canWalk) // true animal.sit() // (2) alert(animal.canWalk) // false
- When
new Animal(name)
is called, the new object recieves__proto__
reference toAnimal.prototype
, see that on the left part of the picture. - Method
animal.sit
changesanimal.canWalk
in the instance, so now this animal object can’t walk. But other animals still can.
The scheme for a pseudo-class:
- Methods and default properties are in prototype.
- Methods in
prototype
usethis
, which is the current object because the value ofthis
only depend on the calling context, soanimal.sit()
would setthis
toanimal
.
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。