JS中级

面向对象三要素:

封装
继承
多态

1.this 详解,事件处理中this的本质

  • window
  • this —— 函数属于谁
	<script type="text/javascript">
	
	var arr=[12,65,87];
	//this:当前的方法,属于谁
	arr.show =function (argument) {
		// body...
		console.log(this);      //[12,65,87]
	}
	arr.show();

 function show(){
 		console.log(this);      //window
	}
	show();
	
	</script>

2.Object 的使用:##

<script type="text/javascript">
var obj = new Object();
obj.aaa = 12;
obj.show = function (argument) {
	console.log(this.aaa); //12
}
obj.show();
</script>

3.工厂方式:

    <script type="text/javascript">
    function createPerson(name, sex) {
        var obj = new Object();
        obj._name = name;
        obj._sex = sex;

        obj.showName = function() {
            console.log('我的名字叫:' + this._name);
        }
        obj.showSex = function() {
            console.log('我是' + this._sex + '的');
        }
        return obj;
    }

    var p1 = createPerson('唐三', '男');
    p1.showName();
    p1.showSex();

    var p2 = createPerson('唐九妹', '女');
    p2.showName();
    p2.showSex();
    </script>

工厂方式的问题:
1.没有new
2.每个对象都有一套自己的函数 —— 浪费资源

4.new的情况:

    <script type="text/javascript">
    function createPerson(name, sex) {
        //var this = Object();
        this._name = name;
        this._sex = sex;

        this.showName = function() {
            console.log('我的名字叫:' + this._name);
        }
        this.showSex = function() {
            console.log('我是' + this._sex + '的');
        }
        //return this;
    }

    var p1 = new createPerson('唐三', '男'); //new 的情况下
    p1.showName();
    p1.showSex();

    var p2 = new createPerson('唐九妹', '女');
    p2.showName();
    p2.showSex();
    </script>
原文地址:https://www.cnblogs.com/tangge/p/7628121.html