面向对象02-构造函数注意事项

2017-05-29  本文已影响0人  肉肉与马甲线的故事

构造函数注意事项

01 函数传值

代码示例

    //001 创建一个构造函数
    function Person(name,age,toDoSomeThing) {

        //002 在构造函数内部设置对象的属性和方法
        this.name = name;
        this.age = age;


        this.toDoSomeThing = toDoSomeThing;
    }

    //003 使用构造函数创建对象
    var zhangsan = new Person("张三",18,function () {
        console.log("张三在读书");
    });

    var lisi = new Person("李四",20,function () {
        console.log("李四在玩耍");
    });

02 类型判断

代码示例

    function Person(name,age) {
        this.name = name;
        this.age = age;
    }

    function Dog(name,age) {
        this.name = name;
        this.age = age;
    }

    var obj1 = new Person("张三",20);
    var obj2 = new Dog("旺财",1);
    console.log(obj1);
    console.log(obj2);

    //判断类型 判断某个对象是否是由制定的构造函数创建出来的
    //instanceOf 语法:对象 instanceOf 构造函数
    //注意点:所有的对象都是Object类型

    console.log(obj1 instanceof Person);       //true
    console.log(obj2 instanceof Person);       //false
    console.log(obj1 instanceof Dog);          //false
    console.log(obj2 instanceof Dog);       //true

    console.log(obj1 instanceof Object);    //true
    console.log(obj2 instanceof Object);    //true

03 构造器属性

function Dog(name) {
        this.name = name;
        this.color = "黄色";
    }
console.log(dog.constructor);  //function Dog(name) {this.name = name;this.color = "黄色";}

04 函数调用

01 构造函数可以像普通函数一样不通过new关键字直接调用;如果函数没有返回值,那么函数调用默认返回undefined

代码示例

    //01 创建构造函数
    function Person() {
        this.name = "张三";
        this.age = 20;
        this.sayName = function () {
            console.log(this.name);
        }
    }

    //02 使用构造函数创建对象
    var p1 =Person();
    console.log(p1);  //undefined

02 在使用构造函数创建对象的时候,如果没有传递参数,则()可以省略

代码示例

       //01 创建构造函数
    function Person() {
        this.name = "张三";
        this.age = 20;
        this.sayName = function () {
            console.log(this.name);
        }
    }

    //02 使用构造函数创建对象
    var p1 = new Person();
    var p2 = new Person;    //说明:如果不需要传递参数,则在调用构造函数的时候()可以省略

05 this指向

01 如果使用new 构造函数的方式调用,则this指向内部默认创建出来的空对象

02 如果像调用普通函数一样调用构造函数,则this指向全局对象window(不要这样使用)

代码示例

    //01 创建构造函数
    function Person(name) {
        if(this==window){
            return new Person(name)
        }
//        if(!(this instanceof Person)){
//        
//            return new Person(name)
//        }
        this.name = name;
    }

    //02 使用构造函数创建对象
    var p1 =Person('zhangsan');
    console.log(p1);  

以上代码显示,不论是否加new调用函数,则均返回新创建的对象

上一篇 下一篇

猜你喜欢

热点阅读