JS之构造函数基础

面试题:new做了几件事?

(porperty(属性) prototype(原型):所有的属性和方法都是放在prototype中的,可以将其理解成仓库,调用属性和方法时可以进去拿)

  1. 创建了新的对象,创建了新的空间;
  2. 改变了this的指向,指向新创建的空间;
  3. 继承了父对象的property属性对象里所有属性和方法

构造函数

<script>
    //window.Constructor();//this ==> window;
    function Constructor(cname,age){
        //属性 和 方法  property method
        //每个空间都有一个this:记录为谁服务过
        //this这个  that那个      var that  = this;(经常用)
        this.cname = cname;//this 谁用了this的空间就指向谁
        this.age = age;
        this.fun = function(){//原始类型  和  引用类型的区别
            //并不是直接把function 存在function Constructor中,而是将地址存在其中且可以改动地址
            console.log(this.cname,this.age);
        };              
        console.log(cname,age);
    }

    var test = new Constructor('xy',18);//此时this指向test
    //在上面的基础上创建一个新的空间,继承上面函数的属性和方法;也可以不加(),new 会自动加
    //可以将构造函数理解成一个躯壳
    //var test =constructor;//将地址赋给test
    //var test =constructor();//将执行结果赋给test
    //test('xy',18);//==>window.test('xy',18);报错,值传不进去
    //console.log(test);

    console.log(test.cname);//xy
    console.log(test.fun());//undefined undefined是test.fun()执行后的结果,输出出来
    //如果在fun里加一个return 2;则执行结果为2;
    test.fun();//执行正确
    //
</script>

改变this指向

<script>
    //window.Constructor();//this ==> window;
    var cname = "xxyy";
    function Constructor(cname,age){
        this.cname = cname;
        this.age = age;
        this.fun = function(){
            console.log(this.cname,this.age);
        };              
        console.log(cname,age);
    }

    var test = new Constructor('xy',18);//此时this指向test
    console.log(test.fun.call(this));
    //call apply bind可以改变this指向 
</script>

构造函数有什么作用?使用场景?和正常函数的区别?
函数是一个实习那某个巨头功能的代码块,是写死的功能;
函数就是一个固定的对象并且没有后代;构造函数有后代;
构造函数是可以把共同的东西写进去之后后代继承都具有并且后代可以添加自己的属性和方法

example

<script>
    function Constructor(name,age) {
        if(!(this instanceof Constructor)){
            return new Constructor(name,age);
        }
        this.name = name;
        this.age = age;
        this.say = function(){
            //document.write("姓名:" + name,"&nbsp;" + "年龄:" + age + "<br/>");
            document.write("姓名:" + this.name,"&nbsp;" + "年龄:" + this.age + "<br/>");
        }
    }
    var test1 = new Constructor('xy',21);
    var test2 = new Constructor('xh',16);
    var test3 = Constructor('xtt',26);
    test1.say();
    test2.say();
    test3.say();
</script>

运行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/ssssssssolo/article/details/82145537