js中this的使用与代码编写

我们在写一个方法的时候,总是会用到一个关键字this,而this的指向就是我们这里所说的执行上下文(执行环境)

首先我们要知道,this指向的永远是调用该方法的对象

function func () {
    this.a = 1;
    console.log(this.a);
}
func();  // 1

代码中方法执行后控制台输出1,由于func是全局对象window下的一个方法,那么调用该方法的对象就应该是全局对象window,所以this理论上指向的对象就应该是window

如果理论成立,而this.a==1,也就是说变量a是一个全局变量。在控制台上直接输入awindow.a后回车,会发现输出了1,所以在func这个方法中,this的指向就是window

var person = {
    name: 'xiao ming',
    age: 18,
    who: function () {
        console.log( 'my name is ' + this.name + ' , ' + this.age + ' years old' );
        console.log( person === this);
    }
}

person.who();

上面这段代码中who方法是person对象的一个属性,被person对象调用,所以this的指向也就是person

通过this实现全选全不选

 	<ul style="display:block;">				
			<li class="parent expanded"><span><input type="checkbox" checked="checked" id="all"/></span><b><img src="${ctx}/static/images/icon_fold_f.png"/></b>
				<a href="javascript:;">网址</a> 
				<ul class="Item" style="display:block">	
				</ul>
			</li>
	$("#all").change(function() {
		if ($(this).attr("checked")) {
			$(".Item").each(function() {
				$(this).attr("checked", true);
			});
		} else {
			$(".Item").each(function() {
				$(this).attr("checked", false);
			});
					}
	})

this可以重写'父类'的方法

var EditView = function(){
    var _this = null;
    var $id = null;
    var key = null;
    var $submit_form = $("#submit_form");
    var $url = "notification/notificationtype";
    var type = null;
    var $add = null;
    var $getById = null;
    var $upd = null;
    this.url = null;
    this.dicurl = "system/dic/getDicByCode/";
    this.uploadUrl = getUploadUrl();
    this.createCusView = null;
    this.getMainData = null;
    this.init = function(){
        if(parent.$("#addwind_frame").contents().length>0){
            $id =  $("#cntenIdKey",parent.$("#addwind_frame").parent().parent().parent()).val();
            $url = $("#cntenUrl",parent.$("#addwind_frame").parent().parent().parent()).val();
            $upd = $("#cntenUpd",parent.$("#addwind_frame").parent().parent().parent()).val();
            $add = $("#cntenAdd",parent.$("#addwind_frame").parent().parent().parent()).val();
            $getById = $("#cntenById",parent.$("#addwind_frame").parent().parent().parent()).val();
        }else if(parent.$("#editwind_frame").contents().length>0) {
            $id =  $("#cntenIdKey",parent.$("#editwind_frame").parent().parent().parent()).val();
            $url = $("#cntenUrl",parent.$("#editwind_frame").parent().parent().parent()).val();
            $upd = $("#cntenUpd",parent.$("#editwind_frame").parent().parent().parent()).val();
            $add = $("#cntenAdd",parent.$("#editwind_frame").parent().parent().parent()).val();
            $getById = $("#cntenById",parent.$("#editwind_frame").parent().parent().parent()).val();
        }else{
            $id =  $("#cntenIdKey",parent.$("#redwind_frame").parent().parent().parent()).val();
            $url = $("#cntenUrl",parent.$("#redwind_frame").parent().parent().parent()).val();
            $upd = $("#cntenUpd",parent.$("#redwind_frame").parent().parent().parent()).val();
            $add = $("#cntenAdd",parent.$("#redwind_frame").parent().parent().parent()).val();
            $getById = $("#cntenById",parent.$("#redwind_frame").parent().parent().parent()).val();
        }

        key = $.util.request[$id];
        type = $.util.request["type"];
        _this = this;
        $Core.OnPageLoad(function () {
            $Core.Loading.HidePageLoading();
        });
        if (key&&key!="") {
            var url = $url+"/getById/" + key;
            if($getById != null && $getById != "" && $getById != "null"){
                url = $getById+"/"+key;
            }
            $.get(url, function (data) {
                _this.getMainData = data;
                $submit_form.form("load", data.data);
                if(type=="red"){
                    $submit_form.form("load", data.data);
                    $("input").attr("readonly", "readonly");
                    $(".easyui-combobox").combo('readonly', true);
                    $(".easyui-combotree").combotree('readonly', true);
                    $('.easyui-textbox').textbox('readonly');
                    $(".easyui-my97").my97('disable');
                    $("#btnSave").hide();
                    $("button").hide();
                    /*$("input",$submit_form).each(function(i,n) {
                        $(n).textbox('disable');
                    });*/
                }
                if(type != "add" && _this.renderSelectors){
                	for(var i=0,len=_this.renderSelectors.length; i<len; i++){
                		var renderSelector = _this.renderSelectors[i],
                			dictDatas = $Core.DicCache.get(renderSelector.settings.dictCode);
                			renderSelector.echoSelect(data, dictDatas);
                	}
                }
            });

        if(_this.createCusView){
            _this.createCusView();
        }
 
    }

    function getUploadUrl() {
        var serviceUrl = $Core.SERVICEPATH();
        var preffix = serviceUrl.substring(0,serviceUrl.lastIndexOf("cnten"));
        var uploadUrl = preffix + "zuul/cnten/plugs/attachment/fileUpload";
        return uploadUrl;
    }
};
var _self = new EditView();
$(function () {
    _self.createCusView = function(){
    	$("#approveState").combobox({
            url: _self.dicurl+'userdevState'
        });
        	$("#customerType").combobox({
        		url: _self.dicurl+'customerType'
        	});
        $("#bottleLibraryWindowFire").combobox({
            url: _self.dicurl+'yesno'
        });
        $("#bottleLibraryWindowOutOpen").combobox({
            url: _self.dicurl+'yesno'
        });
        $("#bottleLibraryGroove").combobox({
            url: _self.dicurl+'yesno'
        });
        $("#installDate").my97({
            minDate:'#F{$(\'#productionDate\').my97(\'getValue\')}'
        });

    }
    
    _self.init = function(){
        key = $.util.request["deviceInstallCheckId"];
        type = $.util.request["type"];
        _this = this;
        $Core.OnPageLoad(function () {
            $Core.Loading.HidePageLoading();
        });
        if (key&&key!="") {
            $.get("security/installapplyvo/getById/" + key, function (data) {
            	debugger;
                _this.getMainData = data;
                $("#submit_form").form("load", data.data);
                
                if(type=="red"){
                    $("input").attr("readonly", "readonly");
                    $(".easyui-combobox").combo('readonly', true);
                    $(".easyui-my97").my97('disable');
                    $(".easyui-combotree").combotree('readonly', true);
                    $("#btnSave").hide();
                    $("button").hide();
                   
                }
                if(type=="edit"){
                   
                }
            });
        }
        if(_this.createCusView){
            _this.createCusView();
        }
    }
    
    _self.init();
	

});

js中this的使用与代码编写_js中this的使用与代码编写

调用重写的createCusView方法

js中this的使用与代码编写_ide_02

js中this的使用与代码编写_js中this的使用与代码编写_03

var EditView = function(){
this.uploadUrl = getUploadUrl();
 function getUploadUrl() {
        var serviceUrl = $Core.SERVICEPATH();
        var preffix = serviceUrl.substring(0,serviceUrl.lastIndexOf("cnten"));
        var uploadUrl = preffix + "zuul/plugs/attachment/fileUpload";
        return uploadUrl;
    }
}

var _self = new EditView();
$(function () {
_self.uploadUrl
});

 

js中this的使用与代码编写_Core_04

this._super();

(function(scope){
	var ListPager = Class.extend({
		init: function(){},
		render: function(){
			var _self = this;
//展示已知数据
				layui.table.render(option);
				
				//渲染部分layui组件
				_self.initLayuiPlugin();
			});
			//界面绘制完成, 初始化界面事件
			_self.initEvent();
		},
		initLayuiPlugin: function(){
			var _self = this;
		},
		initEvent: function(){
			var _self = this;
			//列表 增删改查
			$("div[name='listBtns'] button").unbind('click').bind('click', function(){
				var action = "_self." + $(this).attr("action");
				eval(action);
			});
			
			//列表查询、重置
			$("div button[type='button']",$("#" + _self.container + "-QueryForm"))
				.unbind('click')
				.bind('click', function(){
				var action = "_self." + $(this).attr("action");
				eval(action);
			});
			//二级页面查询a标签
			$("div a[id='search']",$("#" + _self.container + "-QueryForm"))
			.unbind('click')
			.bind('click', function(){
				debugger;
			var action = "_self." + $(this).attr("action");
			eval(action);
		   });
		},
		assemblyFormPrams: function(){	
			//组装列表模糊查询表单数据
			debugger;
			var _self = this;
			var formParam = $("#" + _self.container + "-QueryForm").serializeArray(),
			reqParam = {};
			for(var o in formParam){
				if(formParam[o]["name"]){
					reqParam[formParam[o]["name"]] = formParam[o]["value"];
				}
			}
			return reqParam;
		},
		listQuery: function(){
			debugger;
			var _self = this;
			layui.table.reload(_self.tableId, {
                where: _self.assemblyFormPrams()
            });
		},
	scope.ListPager = ListPager;
})(window);

      <form id="pipeList-QueryForm">
      <div class="side_search">
        <label>开始时间:</label>
        <input type="text" name="startTime" id="test5" placeholder="开始时间"/>
        <label>结束时间:</label>
        <input type="text" name="endTime" id="test6" placeholder="结束事假"/>
        <label>组织机构:</label>
        <select name="organization">
          <option value="一分公司">一分公司</option>
          <option value="二分公司">二分公司</option>
          <option value="三分公司">三分公司</option>
          <option value="四分公司">四分公司</option>
          <option value="五分公司">五分公司</option>
        </select>
        <a id="search" action="listQuery(this,event)">搜索</a>
      </div>
      </form>

	initLayuiPlugin: function(){
		this._super();
		  var table = layui.table;
		  var laydate = layui.laydate;
		    //时间选择器
		  laydate.render({
		    elem: '#test5'
		    ,type: 'time'
		  });
		  
		  laydate.render({
			    elem: '#test6'
			    ,type: 'time'
		});
	},

js中this的使用与代码编写_Core_05

js中this的使用与代码编写_其他_06

js中this的使用与代码编写_Core_07

如果没有super调用不了父类的方法