美文网首页
js构造函数和属性

js构造函数和属性

作者: pretty_rain | 来源:发表于2019-01-25 15:24 被阅读0次

1.四种构造函数方式创建对象

//传统模式
function fun(name){
    this.name = name;
}
fun.prototype={
    init:function(){
       console.log(this.name);
   }
}
var fun = new fun("tom");
//默认形式
function fun1(){
        this.name = "eee";
    }
    fun1.prototype={
        init:function(){
            console.log(this.name);
        }
    }
 /*动态形式*/
    function fun2(){
        this.name="";
    }
    fun2.prototype={
        init:function(){
            console.log(this.name);
        }
    }
    var fun2 = new fun2();
    fun2.name="222";
/* 混合形式*/
     function fun3(name){
         this.name=name;
         this.age=8;
         this.sex='';
     }
     var fun3 = new fun3("333");
     fun3.sex="男";

2.万物皆属性、万物皆对象

/*属性可以是任何*/
 function fun(){
        this.name="";
        this.init=function(){}
    }


/*对象可以是任何*/
    var i=2;
    var name="dddd";
    //报错
    fun1();
    //不报错
    fun();
    //方法会提升到顶部
    function fun(){
    }
    //fun1提升了  但是方法体没有提升
    var fun1 = function(){
    }
    var fu = new fun();

3.set、get 使用方法

    /**
     * 日期设置方法
     * @param date
     * @param format
     * @returns {*}
     */
    function dateFormat(date,format) {
        var o = {
            "M+" : date.getMonth()+1, //month
            "d+" : date.getDate(),    //day
            "h+" : date.getHours(),   //hour
            "m+" : date.getMinutes(), //minute
            "s+" : date.getSeconds(), //second
            "q+" : Math.floor((date.getMonth()+3)/3),  //quarter
            "S" : date.getMilliseconds() //millisecond
        }
        if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
            (date.getFullYear()+"").substr(4- RegExp.$1.length));
        for(var k in o)if(new RegExp("("+ k +")").test(format))
            format = format.replace(RegExp.$1,
                RegExp.$1.length==1? o[k] :
                    ("00"+ o[k]).substr((""+ o[k]).length));
        return format;
    }
    /**
     * 演示set/get方法
     * @constructor
     */
    function Product(){
        this.name='';
        this.price=1000;
        this.date=new Date();
        Object.defineProperty(this,"price",{
            get: function () {return price*0.9;},
            set:function(value){
                if(parseInt(value)>5000){
                    alert("超出范围");
                }else{
                    price = value;
                }
            }
        });
        Object.defineProperty(this,"date",{
            get:function(){
                return dateFormat(date,"yyyy-MM-dd hh:mm:ss");
            },
            set:function(value){
                date=value;
            }
        })
    }
    var product = new Product();
    product.price=4000;
    product.date=new Date();
    console.log(product.price);
    console.log(product.date);

4.权限writable设置

function Product(){
        this.price=99;
        this.name="jwwif";
        Object.defineProperty(this,'price',{
            value:2000,
            //让指定属性不能被写入即不可被改变
            writable:false
        })
    }
    var product = new Product();
    product.price=888;
    //结果是2000
    console.log(product.price);

5.私有属性 、私有方法 、公有属性 、特权方法、原型属性、公有方法、静态属性、静态方法

  • 1.公有属性和公有方法
function User(name,age){
  this.name = name;//公有属性
  this.age = age;
}
User.prototype.getName = function(){//公有方法
  return this.name;
}
var user = new User('fire子海',26);
console.log(user.getName());//output:fire子海

*2.私有属性和方法

function User(name,age){
  var name = name;//私有属性
  var age = age;
  function alertAge(){//私有方法
     alert(age);
  }
  alertAge(age); //弹出26
}
var user = new User('fire子海',26);

*3.静态属性和方法 :无需实例化直接调用

function User(){}
User.age = 26;//静态属性
User.myname = 'fire子海';
User.getName =function(){//静态方法
  return this.myname;//如果这里使用this.name,返回的将是User,所有改用了myname,
}
console.log(User.getName());//output:fire子海
  • 4.特权方法:在构造函数中用this. 写的方法
function User(name,age){
  var name = name;//私有属性
  var age = age;
  this.getName = function(){ //特权方法
     return name;//私有属性和方法不能使用this调用
  }
}
var user = new User('fire子海',26);
console.log(user.getName());//output:fire子海
  • 5.静态类:可以向第三步一样创建 也可以使用字面量的方式创建
var user = {
  init:function(name,age){
   this.name = name;
   this.age = age;
  },
  getName:function(){
   return this.name;
 }
}
user.init('fire子海',26);
console.log(user.getName());//output:fire子海
  • 6.公有方法调用规则
    公有方法中可以通过this调用公有属性、公有方法和特权方法;公有方法中不能通过this调用静态方法和静态属性,只能通过方法名调用,当然也不能调用私有方法和私有属性
function User(){
  this.myname = 'fire子海';//公有属性
  this.age = 26;
  this.do = function(){//特权方法
    return this.myname+'学习js';
  }
}
User.eat = function(food){
 return '晚餐只有'+food;
}
User.prototype.alertAge = function(){
  alert(this.age);
}
User.prototype.alertDo = function(){
  alert(this.do());//调用特权方法
}
User.prototype.alertEat = function(food){
  alert(User.eat(food));//只能通过对象本身调用静态方法
  //alert(this.eat(food))这样调用将出错:this.eat is not a function
}
var user = new User();
user.alertAge();//alert:26
user.alertDo();//alert:fire子海学习js
user.alertEat('方便面')//alert:晚餐只有方便面
  • 7.静态方法的调用规则
    实例对象不能调用静态方法和静态属性
function User(){}
User.age = 26;//静态属性
User.myname = 'fire子海';
User.getName =function(){//静态方法
 
  return this.myname;
}
var user = new User();
console.log(user.getName);//TypeError: user.getName is not a function
user.supper = '方便面';
user.eat = function(){
 return '晚餐只有'+this.supper;
}
user.eat();//晚餐只有方便面

静态方法不能用this调用 公有属性、公有方法、特权方法、私有属性、私有方法、原型属性

function User(){
        this.myname = 'fire子海';//公有属性
        this.age = 26;
        this.do = function(){//特权方法
            return this.myname+'学习js';
        }
    }
    User.prototype.alertAge = function(){//公共方法,也叫原型方法
        alert(this.age);
    }
    User.prototype.sex = '男';//原型属性
    User.phone = "12987898784939";
    User.getPhone = function(){
        //在静态方法中可以用this调用静态属性
        //但是在公有方法中不能用this调用静态属性只能通过类名调用
        return this.phone;
    }
    User.getName= function(){//静态方法
        return this.myname;
    }
    User.getAge = function(){
        this.alertAge();

    }
    User.getDo = function(){
        return this.do();
    }
    console.log(User.getPhone());//12987898784939
    console.log(User.getName())//undefined
    console.log(User.getDo());//TypeError: this.do is not a function
    console.log(User.getAge())//TypeError: this.alertAge is not a function
  • 8.特权方法的调用规则
    特权方法中可以通过this调用公有属性、公有方法、特权方法,可以直接调用私有属性、私有方法,不能通过this调用静态方法和属性但是可以通过类名调用
function User(girlfriend){
        var girlfriend = girlfriend;
        function getGirlFriend(){
            return '我女朋友'+girlfriend+'是美女!';
        }
        this.myname = 'fire子海';//公有属性
        this.age = 26;
        this.do = function(){//特权方法
            return this.myname+'学习js';
        }
        this.alertAge = function(){
            this.changeAge();//特权方法调用公有方法
            alert(this.age);
        }
        this.alertGirlFriend = function(){
            alert(getGirlFriend());//调用私有方法
        }
        this.getPhone = function(){
            //alert(this.phone);//undefind
            alert(User.phone);
        }
    }
    User.prototype.changeAge = function(){
        this.age = 29;
    }
    User.phone = "423423423432";
    var user = new User('某某');
    user.alertAge();//alert:29
    user.alertGirlFriend();//alert:我的女朋友某某是美女!
    user.getPhone();

*9.私有方法
对象的私有方法和属性,外部是不可以访问的,在方法的内部不能this调用对象的公有方法、公有属性、特权方法的

function User(girlfriend){
   var girlfriend = girlfriend;
  this.myname = 'fire子海';//公有属性
  this.age = 26;
  function getGirlFriend(){ 
   //this.myname ;//此时的this指向的window对象,并非User对象,
    // this.myname = 'fire子海',此时的this指向的是getGirFriend对象了。
  //如果通过this调用了getGirFriend中不存在的方法呀属性,this便会指向window 对象,只有this调用了getGirlFriend存在的方法和属性,this才会指定getGirlFriend;
     alert(User.eat('泡面'));//alert:晚餐只有方便面
  }
  this.do = function(){//特权方法
    return this.myname+'学习js';
  }
  this.alertAge = function(){
   this.changeAge();//特权方法调用公有方法
    alert(this.age);
  }
  this.alertGirlFriend = function(){
   getGirlFriend();//调用私有方法
  }
}
User.eat = function(supper){
 return '晚餐只有'+supper;
}
var user = new User('某某');
user.alertGirlFriend();
  • 面试题
function Fun(){
        this.name="peter";
        return{
            name:'tom'
        }
    }
    console.log(new Fun().name);
    function Fun1(){
        this.name="peter";
        return 'tom'
    }
    console.log(new Fun1().name);

6.init公有方法与config公有属性的习惯写法

function Product(option){
        this._init(option);
        this.config={
            name:document.querySelector(".aaa"),
            account:document.querySelector(".bbb")
        }
    }
    Product.prototype={
        _init:function(option){
            this.age=option.age;
        }
    }

7.检测数据类型

  // jQuery判断
    //    jQuery.isArray():是否为数组。
    //    jQuery.isEmptyObject():是否为空对象(不含可枚举的属性)。
    //    jQuery.isFunction():是否为函数。
    //    jQuery.isNumeric():是否为数字。
    //    jQuery.isPlainObject():是否为使用“{}”或“new Object”生成的对象,而不是浏览器原生提供的对象。
    //    jQuery.isWindow():是否为window对象。
    //    jQuery.isXMLDoc():判断一个DOM节点是否处于XML文档之中。
    var a;
    console.log(typeof 1);
    console.log(typeof "1");
    console.log(typeof true);
    console.log(typeof document.documentElement);
    console.log(typeof a);
    console.log(typeof []);
    console.log(typeof {});
    console.log(typeof null);
    //contructor也可以判断
    console.log(toString.call(1));
    console.log(toString.call("1"));
    console.log(toString.call(true));
    console.log(toString.call(document.documentElement));
    console.log(toString.call(a));
    console.log(toString.call([]));
    console.log(toString.call({}));
    console.log(toString.call(null));

相关文章

  • js构造函数和属性

    1.四种构造函数方式创建对象 2.万物皆属性、万物皆对象 3.set、get 使用方法 4.权限writable设...

  • 原型链继承

    构造函数的prototype属性 实例和构造函数和原型父构造函数的实例作为子构造函数prototype属性,则实现...

  • JS原型

    JS原型 构造函数和对象 函数的prototype 函数具有prototype属性,它的指向是什么呢?答案是: 它...

  • kotlin类的构造函数和属性

    一、 类的构造函数和属性 二、主构造函数中定义属性 2.2: 三、主构造函数和次构造函数 四、构造参数有默认值的情况

  • 2018-07-11

    JS原型和原型链 1.每个构造函数生成实例的时候 会自带一个constructor属性 指向该构造函数 实例.co...

  • JS组合继承(寄生继承)

    js中new和Object.create的区别(简单描述): new 产生的实例,优先获取构造函数上的属性;构造函...

  • JS - 原型,prototype 和 __proto__

    原型和原型链是JS实现继承的方式。除了箭头函数,其它函数身上都有prototype属性。当该函数作为构造函数生成对...

  • JavaScript--构造函数

    私有属性:定义在构造函数内部的变量和函数;不能在构造函数之外的访问变量和函数。公有属性:能够被构造函数创建的所有对...

  • 关于构造函数Array属性和方法总结

    @(JavaScript基础) 关于构造函数Array属性和方法总结 构造函数Array属性: Array.len...

  • prototype小结

    ### prototype 小结 - 构造函数有prototype属性指向其对应的原型对象: ```js // a...

网友评论

      本文标题:js构造函数和属性

      本文链接:https://www.haomeiwen.com/subject/vppmjqtx.html