js小结
1)Closures 闭包
var x = function() {
var i = 0;
return function() {
return ++i;
}
};
var f = x();
document.write("first: " + f());
document.write(", second: " + f());
2)Polymorphism 多态性
var animal = function() {
var legs = 4;
var nipples = 2;
this.getLegs = function() { return legs; };
this.getNipples = function() { return nipples; };
};
var dog = function() {
animal.call(this);
this.getNipples = function() { return 8; };
}
var human = function() {
animal.call(this);
this.getLegs = function() { return 2; };
}
var lassie = new dog();
var hubert = new human();
document.write("dog: " + lassie.getLegs() + "/" + lassie.getNipples());
document.write(", human: " + hubert.getLegs() + "/" + hubert.getNipples());
3)Call
var blog = function() {
this.type = "blog";
this.getType = function() {
return this.type;
}
}
var joshuasBlog = new blog();
document.write(joshuasBlog.getType() + "->" + joshuasBlog.getType.call({ type: "hehehe" }));
4)Prototype 原型
var y = function(value) {
this.superValue = value;
this.getSuperValue = function() { return this.superValue; }
}
var x = function(value) {
this.value = value;
this.getValue = function() { return this.value; }
}
x.prototype = new y(123);
var a = new x(1);
var b = new x(2);
document.write("a.value: " + a.getValue());
document.write(", b.value: " + b.value);
document.write(", a.superValue: " + a.getSuperValue());
document.write(", b.superValue: " + b.superValue);
答案:
Closures: first: 1, second: 2 Polymorphism: dog: 4/8, human: 2/2 Call: blog->hehehe Prototype a.value: 1, b.value: 2, a.superValue: 123, b.superValue: 123

浙公网安备 33010602011771号