方法调用:
使用bind方法:
使用高阶函数:
arguments对象:
arguments.caller/arguments.callee/caller;
函数对象的toString方法:
new操作构造函数:
在使用构造函数时可能忘记new,一般可以将构造函数写为:
function User(name, password) { if(!(this instanceof User)) { return new User(name, password); } this.name = name; this.password = password; }
但它需要额外函数调用,可以选择更优方法:
function User(name, password) { var self = this.instanceof User ? this : Object.create(User.prototype); self.name = name; self.password = password; return self; }
对于没有Object.create方法,可以简单实现其单参数方法
Object.create = function(prototype) { function C() {}; C.prototype = prototype; return new C(); }
私有数据:
构建子类/父类继承:
function Scene(context, width, height, images) { this.context = context; this.width = width; this.height = height; this.images = images; this.actors = []; } Scene.prototype.register = function(actor) { this.actors.push(actor); } Scene.prototype.unregister = function(actor) { var i = this.actors.indexOf(actor); if(i >= 0) { this.splice(i,1); } } Scene.prototype.draw = function() { this.context.clearRect(0, 0, this.width, this.height); for(var a = this.actors, i = 0, n = a.length; i < n; i++) { a[i].draw(); } } //--------------------------------- function Actor(scene, x, y) { this.scene = scene; this.x = x; this.y = y; scene.register(this); } Actor.prototype.moveTo = function(x, y) { this.x = x; this.y = y; this.scene.draw(); } Actor.prototype.exit = function () { this.scene.unregister(this); this.scene.draw(); } Actor.prototype.draw = function() { varimage = this.scene.images[this.type]; this.scene.context.drawImage(image, this,x, this,y); } Actor.prototype.width = function() { return this.scene.images[this.type].width; } Actor.prototype.height = function() { return this.scene.images[this.type].height; } //--------------------------------- function SpaceShip(scene, x, y) { Actor.call(this, scene, x, y); this.points = 0; } SpaceShip.prototype = Object.create(Actor.prototype); SpaceShip.prototype.type = 'spaceShip'; SpaceShip.prototype.scorePoint = function() { this.points++; } SpaceShip.prototype.left = function() { this.moveTo(Math.max(this.x - 10, 0), this.y); } SpaceShip.prototype.right = function() { var maxWidth = this.scene.width - this.width(); this.moveTo(Math.min(this.x + 10, maxWidth), this.y); }
function SpaceShip(scene, x, y) { Actor.call(this, scene, x, y); this.points = 0; }
SpaceShip.prototype = Object.create(Actor.prototype);
避免继承标准类:继承标准类往往会由于一些特殊的内部属性而破坏;
猴子补丁: