JavaScript面向对象
创建对象:js不能定义类,但是能直接创建对象
1.创建对象-字面型对象:
通过key:value来创建
var Person= { name:"hk", age:20, print:function() { console.log("name is "+ this.name + " age is "+this.age); } } var p=Person; p.age=15; p.print();
2.创建对象-Object.create(ARG)
函数Object.create能在已知的对象创建一个新对象
var Person={ name:"hk", age:20, print:function() { console.log("name is "+ this.name + " age is "+this.age); } } var p=Object.create(Person); p.age=15; p.print(); Person.print();
3.创建对象-使用构造函数:(类似于C++ java等创建对象)
function Person(name,age){ this.name=age; this. age=age; this.print=function() { console.log("name is "+ this.name + " age is "+this.age); } } var p=new Person("hk",20); p.print();
原型Prototype:可以扩展对象的函数和属性 还可以达到继承的效果,是继承的基础(如lua中的metatable)
function Person(name, age) { this.name = name; this.age = age; this.print = function () { console.log("name is " + this.name + " age is " + this.age); } } var p = new Person("hk", 20); Person.prototype.growUp= function() { this.age++; } Person.prototype.address = "12346"; p.growUp(); p.print(); console.log(p.address);
继承:利用cocos2dx-js提供的Class.extend
var MapData=cc.Class.extend( { ... }); var MapUI=MapData.extend( { ... });