Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

mixins and native

  • Loading branch information...
commit 5c28bcc5cfa169267b36d341c9ce07547f6e79d8 1 parent dea3219
@voloko authored
Showing with 72 additions and 1 deletion.
  1. +26 −0 prototypes/04_mixins.js
  2. +43 −0 prototypes/05_native.js
  3. +3 −1 runner.html
View
26 prototypes/04_mixins.js
@@ -3,6 +3,32 @@ h('mixins');
var AnimalLike = {
walk: function() {
return "I'm walking";
+ },
+
+ talk: function() {
+ return "I'm " + this.name;
}
};
+var Dog = function() {
+ this.name = 'Grommit';
+};
+for (var i in AnimalLike) {
+ Dog.prototype[i] = AnimalLike[i];
+}
+
+var Cat = function() {
+ this.name = 'Kitty';
+};
+for (var i in AnimalLike) {
+ Cat.prototype[i] = AnimalLike[i];
+}
+
+
+var dog = new Dog();
+var cat = new Cat();
+
+print('dog can walk: ', dog.walk());
+print('cat can walk: ', cat.walk());
+print('dog can talk: ', dog.talk());
+print('cat can talk: ', cat.talk());
View
43 prototypes/05_native.js
@@ -0,0 +1,43 @@
+h('chaning native prototype');
+
+Array.prototype.mult2 = function() {
+ for (var i = 0; i < this.length; i++) {
+ this[i] = this[i] * 2;
+ }
+};
+
+var arr = [1, 2, 3];
+print('I was: ', arr);
+arr.mult2();
+print('I become: ', arr);
+
+
+
+h('this leads to side effects');
+for (var i in arr) {
+ print('Found in arr: ', i);
+}
+print('mult2? WTF?');
+
+
+
+h('changing object prototype is usualy bad');
+Object.prototype.keys = function() {
+ var result = [];
+ for (var i in this) {
+ if (this.hasOwnProperty(i)) {
+ result.push(i);
+ }
+ }
+ return result;
+};
+
+var obj = {
+ foo: 'bar',
+ bar: 'foo'
+};
+print('keys of an object: ', obj.keys());
+for (var i in obj) {
+ print('Found in obj: ', i);
+}
+print('keys? WTF?');
View
4 runner.html
@@ -32,6 +32,8 @@
window.printh = window.h = printh;
})();
</script>
- <script src="prototypes/03_inheritance.js" type="text/javascript" charset="utf-8"></script>
+
+ <!-- change the src in this script -->
+ <script src="basics/01_variables.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
Please sign in to comment.
Something went wrong with that request. Please try again.