js构造函数和属性

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));
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,122评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,070评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,491评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,636评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,676评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,541评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,292评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,211评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,655评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,846评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,965评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,684评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,295评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,894评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,012评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,126评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,914评论 2 355