对象定义-原型对象-回调函数

JavaScript类定义类和对象

  • 创建一个对象,给这个对象一个color属性
var obj=new Object();
obj.color="red";
  • 原型对象prototype
function User(){}
User.prototype.nation='usa';
var u1=new User();
var u2=new User();
alert(u1.nation)
alert(u1.nation)

弹出的都是‘usa’,nation就是User类的属性,u1,u2都有这个属性

function User(){}
var u1=new User();
var u2=new User();
u.nation='usa';

这上面的nation就只是u1的属性,u2没有

  • 为一个类增加一个方法作为他的属性
    var date=new Date();
    Date.prototype.dateFormat=function () {
        var year=this.getFullYear();
        var month=this.getMonth()+1>9 ? this.getMonth()+1:'0'+(this.getMonth()+1);
        var day=this.getDate();
        var hour=this.getHours();
        var minute=this.getMinutes();
        var second=this.getSeconds();

        return year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;
    }

    console.log(date.dateFormat());

上面的dateFormat()就成了Date的一个属性,this就是date

  • 回调函数的使用
    使用回调函数的原因是js是一种单线程,异步的语言
function add(m,n,callback){
//2000毫秒后执行function
setTimeout(function(){
var c=m+n;
callback(c)
},2000)
}
function show(res){
console.log(res)
}
add(20,30,show);

先是调用add函数,add又返回调用show函数,最终在2秒后输出50
化简上面的代码

function add(m,n,callback){
setTimeout(function(){
var c=m,n;
callback(3)
},2000)
}
add(m,n,function(res){
console.log;
})
  • this的使用方法

    ```
        var user={
            name:'tom',
            show:function () {
                var that=this;
                setTimeout(function () {
                    console.log(that.name);
                },2000);
            }
        }
        user.show();
        ```
    

    这里的this指的是user

  • 用js的方法给网页界面添加一组按钮
var btn=document.queryselect('#con_btn')
for(var i=1;i<=10;i++){
btn.innerHTML+='<button>${i}</button>'
}

界面上会显示十个按钮

猜你喜欢

转载自blog.csdn.net/qq_42650983/article/details/81024070