标签:面向对象 javascript
方法一:构造函数法function Cat(){ this.name = ""; } Cat.prototype.showName = function(){ console.log(this.name); } var cat = new Cat(); cat.name = "Tom"; cat.showName();// Tom
var Cat = { name:"", showName:function(){ console.log(this.name); } }; var cat = Object.create(Cat); cat.name = "Tom"; cat.showName();// Tom
var Cat = { createNew:function(){ var cat = {}; cat.name = ""; cat.showName = function(){ console.log(this.name); } return cat; } }; var cat = Cat.createNew(); cat.name = "Tom"; cat.showName();// Tom
var Animal = { createNew:function(){ var animal = {}; animal.name = ""; animal.sleep = function(){ console.log("ZZzz..."); } return animal; } }; var Cat = { createNew:function(){ var cat = Animal.createNew(); cat.name = "Cat"; cat.showName = function(){ console.log(this.name); } return cat; } }; var cat = Cat.createNew(); cat.name = "Tom"; cat.showName();// Tom cat.sleep();// ZZzz...
var Cat = { createNew:function(){ var cat = {}; var name = "Tom";// 私有 cat.showName = function(){ console.log(name); } return cat; } }; var cat = Cat.createNew(); cat.showName();// Tom
var Cat = { className:"Cat", createNew:function(){ var cat = {}; cat.name = "";// 私有 cat.showName = function(){ console.log(cat.name); } cat.showClass = function(){ console.log(Cat.className); } return cat; } }; var cat1 = Cat.createNew(); cat1.name = "Tom"; cat1.showName(); cat1.showClass(); var cat2 = Cat.createNew(); cat2.name = "Jim"; cat2.showName(); cat2.showClass();
标签:面向对象 javascript
原文地址:http://blog.csdn.net/xufeng0991/article/details/45218117