js中this的四种调用模式

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>



<script type="text/javascript">

    //this的四种调用模式(this作用域)
  //在此声明,this仅仅是一个作用域的关键字,为了区分变量的作用域。(构造器调用模式)
  
/** * 方法调用模式 * 当一个函数被保存为对象的一个属性时,我们称它为一个方法,当方法被调用时,this指向该对象 * @type {{value: number, getValue: getValue}} */ var obj = { value : 'getValue() in Object', getValue : function() { alert(this.value); } }; obj.getValue(); //alert 1 /** * 函数调用模式 * 当一个函数并非一个对象的属性时,它被当做一个函数来调用,此时的this指向全局变量(window) * @type {string} */ window.value = 'getValue() not in Object'; function getValue() { alert(this.value); } getValue(); /** * 构造器调用模式 * 结合new前缀调用的函数被称为构造器函数,此时的this指向构造器函数的实例对象 * @param val */ function show(val){ this.value = val; //value = val; } show.prototype.getVal = function() { alert(this.value); //alert(value); show()方法中省略this,此处省略this可以显示正常结果。原因:变量提升。 }; var func = new show('constructor'); func.getVal(); /** * apply/call调用模式,对象冒充 * * @param str */ var fun = function(str) { this.stauts = str; }; fun.prototype.getStatus = function () { alert(this.status); }; var obj = { status : 'loading' }; fun.prototype.getStatus.apply(obj);  
  //相当于
fun.prototype.getStatus.apply(obj, null); 
</script> </head> <body> </body> </html>

 

你可能感兴趣的:(this)