javascript - 原型定义的变量的问题

查看:155
本文介绍了javascript - 原型定义的变量的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

想问大家一个问题,为什么看到别人写的类,属性都挂在this上?不可以放在方法里吗?比如

function GetMusic($content) {
  this.content = $content;
  this.title = this.content.find(".title");
}
GetMusic.prototype.changTitle = function() {
  this.title.toggleClass("on");
  }
}

为什么不这样写

function GetMusic($content) {
  this.content = $content;
}
GetMusic.prototype.changTitle = function() {
  var title = this.content.find(".title");
  title.toggleClass("on");
  }
}

就是为什么有时候这个变量只用一次也挂在实例上,就是用this挂起来。那么其实:
第一种:

 function GetMusic($content) {
      this.content = $content;
      this.title = this.content.find(".title");
    }

第二种

function GetMusic($content) {
      this.content = $content; 
    }
    GetMusic.prototype.changTitle = function() {
     this.title = this.content.find(".title");
      }
    }

第三种

 function GetMusic($content) {
      this.content = $content; 
    }
    GetMusic.prototype.changTitle = function() {
     var title = this.content.find(".title");
      }
    }

上面的三个title变量有什么不一样?对性能什么的有什么印象?一般什么情况下用哪种?

解决方案

LZ你要干嘛?


对于以下:

第二种

第三种

问题:
为什么我每次调用changTitle的时候你都给我执行this.content.find函数、而且每次结果都是title,不累吗?


对于以下:

GetMusic.prototype.changTitle = function() {
    var title = this.content.find(".title");
 }

问题:
如果我现在有个其他函数,叫什么changTitleColor:

GetMusic.prototype.changTitleColor= function() {
 var title = this.content.find(".title");
 //title.style.color = 'xxxx';
}

//如果保存了this.title的属性的话就可以这样
GetMusic.prototype.changTitleColor= function() {
 //this.title.style.color = 'xxxx';
}

上面又重复了this.content.find(".title")这个方法,不累吗?


其实,这里要考虑的不是性能,而是封装,也即是到底这个this.title是不是和GetMusic强相关;如果是的话,那就把title给容纳进来、作为GetMusic内部一部分;如果this.titleGetMusic相关性很小,那也就没必要保存this.title这个属性;
也就是分清楚哪里是内部、哪里是外部。

这篇关于javascript - 原型定义的变量的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆