js创建类的方式有几种,大致如下:
1,构造函数方式:
function Car(parameters) { this.name = "objectboy"; } var cat1 = new Car(); console.log(cat1.name);
2,Object.create()
var Cat = { name: "大毛", makeSound: function(){ alert("喵喵喵"); } }; var cat1 = Object.create(Cat); alert(cat1.name); // 大毛 cat1.makeSound(); // 喵喵喵
感觉有点复杂
3,最简单的方式
var Car = { CreateNew: function() { var cat = {}; cat.name = "objectboy"; cat.age = 26; cat.makeJS = function() { alert("我是objectboy"); }; return cat; } }; var cat1 = Car.CreateNew(); console.log(cat1.name); cat1.makeJS();
个人认为第三种从理解方面来说是最好的,
继承特性:
var sl = { CreateNew: function () { var cat = {}; cat.sleep = function() { alert("objectboy在睡觉"); }; return cat; } }; //先定义一个需要继承的类 var Car = { CreateNew: function() { var cat = sl.CreateNew(); cat.name = "objectboy"; cat.age = 26; cat.makeJS = function() { alert("我是objectboy"); }; return cat; } }; var cat1 = Car.CreateNew(); console.log(cat1.name); cat1.makeJS(); cat1.sleep(); //调用继承方法