日期:2014-05-16 浏览次数:20411 次
var person = { name:null, setName:function(name){ this.name = name; return this.name; }, getName:function(){ alert(this.name); } }
var Person = function(){ this.name = null; } Person.prototype.setName = function(name){ this.name = name; } Person.prototype.getName = function(){ alert(this.name); }
(function(){ var name; var setName = function(n){ name = n; } window['person']['setName'] = setName; var getName = function(){ alert(name); } window['person']['getName'] = getName; })()
var person = function(){ var name = null; return{ setName:function(n){ name = n; }, getName:function(){ alert(name); } } }
var Person = function(){ this.name = null; } Person.prototype = { setName:function(name){ this.name = name; return this; }, getName:function(){ alert(this.name); return this; } }
var p = new Person(); p.setName('Tom').getName().setName('Ray').getName();
var Person = function(){ this.name = null; } Person.prototype.setName = function(name){ this.name = name; } Person.prototype.getName = function(){ alert(this.name); } Person.prototype.getAge = function(){ var age = this.age || ''; alert(age); }
本人比较熟悉的就是这几种方式了,每个人都有每个人的特色,所以方式也是说不尽的.但是借此,我想探讨以下几个问题: 1.有关于this指针 在建立多种类的时候都用到this,可是this的作用究竟是什么,而其实this在重用和继承上起着很大的作用.我们先看看一个关于继承的例子: 首先建立Person类: var Person = function(){ this.name = null; } Person.prototype.setName = function(name){ this.name = name; } Person.prototype.getName = function(){ alert(this.name); } Person.prototype.getAge = function(){ var age = this.age || ''; alert(age); } 然后在建立一个Children类,并集成Person的所有方法和属性: var Children = function(age){ this.name = null; this.age = age; } Children.prototype = new Person(); //继承Person的属性和方法 Children.prototype.ageJudge = function(){ //另外为Children添加新方法 if(this.age > 18){ alert('成年人~'); } else { alert('未满18岁呢~'); } } Children.prototype.getName = function(){ //重写getName方法 var about = this.name + ' ' + this.age; alert(about); } var tom = new Children(12); var ages = tom.getAge(); //12 var judge = tom.ageJudge(); //未满18岁呢~ var setN = tom.setName('Tom'); var get = tom.getName(); //Tom 12 这就是继承,然后我们看个简单的函数重用: var SetColor = function(){ this.style.backgroundColor = '#000