• js 定义函数的几种方法 以及如何调用


    /*1.方法调用模式:
        先定义一个对象,然后在对象的属性中定义方法,通过myobject.property来执行方法,this即指当前的myobject 
        对象。*/
            var car = {
                carId:123,
                carName:"奥迪",
                carColor:"red",
                say:function(){
                    console.log(this.carName+" color is "+this.carColor);
                }
            };
            car.say();
    
        /*2.函数调用模式
        定义一个函数,设置一个变量名保存函数,这时this指向到window对象。*/
            var mycar = function(name,color){
              return "my car is " +color+" and "+name ;
            }
            console.log(mycar("奥迪","红色"));
    
        /*3.构造器调用模式
        定义一个函数对象,在对象中定义属性,在其原型对象中定义方法。在使用prototype的方法时,必须实例化该对象才能调用其方法。*/
            var yourcar = function(name,color){
                this.name = name;
                this.color = color;
            };
            yourcar.prototype ={
                say:function(){
                    console.log("your car is " +this.name + " and " +this.color);
                }
            };
            var yourcar = new yourcar("奔驰","蓝色");
            yourcar.say();
    
        /*4.apply,call调用模式*/
            function count(num1, num2) { 
                return num1 + num2; 
            } 
            console.log(count.call(window, 10, 10)); //20 
            console.log(count.apply(window,[10,20])); //30
    
            window.a=100;
            window.b=300;
            var myobject={a:40,b:50};
            var sum = function(){
              return this.a+this.b;
            };
            var sum1 = sum.call(window); 
            // var sum2 = sum.call(myobject);
            var sum2 = sum.apply(myobject); 
            console.log(sum1+"========="+sum2);
    
            // 发现apply()和call()的真正用武之地是能够扩充函数赖以运行的作用域,如果我们想用传统的方法实现
            window.a=100;
            window.b=300;
            var myobject={a:40,b:50};
            function sum(){
                console.log(this.a+this.b);
            }
            console.log(sum());
            myobject.sumnumber = sum;
            console.log(myobject.sumnumber());
    
            window.color = "red"; 
            var o = { color: "blue" }; 
            function sayColor(){ 
                console.log(this.color); 
            } 
            sayColor();
            var OSayColor = sayColor.bind(o); 
            OSayColor(); //blue
    
    
  • 相关阅读:
    在UNICODE编码格式下, CString 转换为 char* :
    inet_ntop(), inet_pton(), htonl(), ntohl()
    'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)'
    NMAKE:fatal error U1077.“...cl.exe” return code 0xc0000135
    拷贝(复制)构造函数和赋值函数
    GIS 地图中术语解释
    Linux 下防火墙端口设置
    LInux 下安装jdk
    ln 命令
    zip命令
  • 原文地址:https://www.cnblogs.com/zhuliming-java/p/5395625.html
Copyright © 2020-2023  润新知