js基础——面向对象(构造函数)

1、面向对象:类的标志,通过类可创建多个具有相同属性和方法的对象
2、创建对象
1)工厂模式方式:避免重复实例化但未能解决识别问题
 function boss(name, age) {
          var obj = new Object();
          obj.name = name;
          obj.age = age;
          obj.run = function () {
            return "姓名:" + this.name + ",年龄:" + this.age + ",我们都从属于boss"
          };
          return obj;
        }
        var boss1 = new boss("张三", 58);
        console.log(boss1.run());
        var boss12 = new boss("李四", 58);
        console.log(boss12.run());
        console.log(typeof boss1);//object
        console.log(boss1 instanceof boss);//false,不属于boss属于object,很难区分
2)(构造函数方式:避免重复实例化并能解决对象识别问题)
  function Boss(name,age) {
          this.name = name;
          this.age = age;
          this.run = function () {
            return "姓名:"+this.name+",年龄:"+this.age+",我们都从属于Boss"
          };
        }
        var employee1= new Boss("张三",18);//创建对象
        console.log(employee1.run());
        var employee2= new Boss("李四",25);
        console.log(employee2.run());
  console.log(employee1 instanceof Boss);//true
构造函数里的方法run()可以用new Function来代替
this.run = new Function (" return \'姓名:\' + this.name + \',年龄:\' + this.age + \',我们都从属于Boss\'");
构造函数特点:
1.没有显示的创建对象(new Object)
2.直接将属性和方法赋值给this对象
3.没有return语句
4.函数名和实例化构造名相同且大写,便于区别普通函数
5.通过构造函数创建对象,必须使用new运算符。(调用)
6.在构造函数体内,this代表当前构造函数所声明的对象。
 

猜你喜欢

转载自www.cnblogs.com/LindaBlog/p/10984187.html