您的位置:知识库 » Web前端

JavaScript对象探讨

作者: 蓝色理想  来源: 蓝色理想  发布时间: 2009-12-14 09:59  阅读: 1934 次  推荐: 0   原文链接   [收藏]  

  本人比较熟悉的就是这几种方式了,每个人都有每个人的特色,所以方式也是说不尽的.但是借此,我想探讨以下几个问题:

  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'; //this指向window
}
document.body.onclick
= SetColor; //此时this指向body
documnet.getElementById('color').onmouseout = SetColor;//this指向documnet.getElementById('color')

  看了this的作用之后,想必对this有了新的认识了吧.现在就有疑问了,就是this的该用与不该用,下面在看个简单的例子:

var setColor = {
init:
function(obj){
this.obj = obj; //this指向setColor
this.obj.onclick = this.color;
},
color:
function(){
this.style.backgroundColor = '#000'; //this指向obj
}
}

  就在一个类里,this却指向2处地方,有时这样总会让人觉得困惑.刚学习的人更会被this弄的晕头转向.而稍稍改变一下写代码的方式:

var setColor = {
init:
function(obj){
setColor.obj
= obj;
setColor.obj.onclick
= setColor.color;
},
color:
function(){
this.style.backgroundColor = '#000'; //this可以方便方法的重用
}
}

  这样一下来,代码可以更加的清晰了.所以编写代码的时候应该考虑好究竟今后的用途,还有能否重用.如果明确了不进行继承或是重用,个人觉得应该尽可能的避免使用this,更有个比较常出现的问题.如下:

var Person = function(){
this.name = null;
}
Person.prototype.setName
= function(name){
this.name = name;
}
Person.setName(
'tom'); //错误方式此时setName方法中的this将指向Person.prototypel,Person并没有setName方法

  前面讲过,若果不写成var p = new Person();p.setName('tom');该类里的this将会直接指向Person.prototypel.这种错误在编译时,还是运行时都不会报错.有时会造成让人很头痛的问题.所以在编写代码时,我总是很慎重的选用this.

0
0
 
标签:JavaScript

Web前端热门文章

    Web前端最新文章

      最新新闻

        热门新闻