面向对象的javascript是这门语言被设计出来时就考虑的问题,熟悉OOP编程的概念后,学习不同的语言都会发现不同语言的实现是不同的,javascript的面向对象特性与其他具有面向对象特性的语言的实现的区别比较大,通过不断编程实践才能逐渐体会到面向对象的优点从而形成自己独特的javascript面向对象实现方式,这也是编写可重用代码的关键。
var obj = new Object(); var objRef = obj; obj.oneProperty = 1; alert(obj.oneProperty == objRef.oneProperty);//显示true var items = new Array("1","2","3"); var itemsRef = items; items.push("4"); alert(items.length == itemsRef.length);//结果是true,因为Array对象将数组元素作为其属性对象保存 items = new Array("one","two","three"); alert(items != itemsRef); //结果true,已经是两个不同的对象了
变量 | typeof的值 | 变量.constructor |
---|---|---|
{an:"object"} | "object" | Object |
["an","array"] | "object" | Array |
function(){} | "function" | Function |
"a string" | "string" | String |
55 | "number" | Number |
true | "boolean" | Boolean |
function delayAlert(msg,time){ setTimeout(function(){ alert(msg); }, time); } delayAlert("welcome", 2000);//调用代码清晰简洁 function add(num){ return function(toAdd){return num + toAdd}; } var addFive = add(5); alert(add(4) == 9); //结果true,闭包实现函数的Curry化 var obj = document.getElementById("main"); var items = ["click", "keypress"]; for(var i = 0; i < items.length; i++){ (function(){ var item = items[i]; obj["on" + item] = function(){alert(item);}; })(); } //使用匿名函数激发出作用域,for循环中获得当前循环时的i值
function changeColor(color){ this.style.color = color; } changeColor.call(document.getElementById("main"), "black");
function User(properties){ for( var i in properties){ (function(which){ var p = i; which["get" + p] = function(){return properties[p];}; which["set" + p] = function(){properties[p] = val;}; })(this);) } } //特权方法实例 var user = new User({name:"Bob",age:44}); alert(user.name == null); //没有name属性 alert(user.getname() == "Bob");//动态获取属性 user.setage(22); alert(user.getage() == 22);//动态获取
function Person(name){this.name = name;}; Person.prototype.getName = function(){return this.name;}; function User(name, password){this.name = name; this.password = password;}; User.prototype = new Person(); User.prototype.getPassword = function(){return this.password;};其中User对象的原型prototype设置为一个Person对象,因此每当实例化User对象时,得到的每个User对象都会带有Person对象所有的方法,从而如同操作Person对象一样。这个技巧可以简化javascript的继承而编写一系列的包装函数。
//继承自单一函数。将新函数绑定到对象的prototype上 Function.prototype.method = function(name, func){ this.prototype[name] = func; return this; }; Function.method('inherits', function(parent){var this.prototype = new parent(); return this;}); //从单一父对象继承所有内容 Function.method('swiss', function(parent){ for (var i = 1; i < arguments.length; i++){ var name = arguments[i]; this.prototype[name] = parent.prototype[name]; } return this; });改进原型式继承的代码:
function Person(name){this.name = name;}; Person.method("getName", function(){}return name;); function User( name, password){ this.name = name; this.password = password; }; User.inherits( Person); User.method('getPassword', function(){return this.password;}); User.method('getName', function(){return this.name;});