零JS筆記 | apply call 轉

call: 调用一个对象的一个方法,以另一个对象替换当前对象。

call([thisObj[, arg1[, arg2[, [,.argN]]]]])

參數:thisObj,


arg1, arg2, , argN :可选项。将被传递方法参数序列。


說明:call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。

说明白一点其实就是更改对象的内部指针,即改变对象的this指向的内容。这在面向对象的js编程过程中有时是很有用的。
    function Obj(){this.value="对象!";}
    var value="global 变量";
    function Fun1(){alert(this.value);}

    window.Fun1();   //global 变量
    Fun1.call(window);  //global 变量
    Fun1.call(document.getElementById('myText'));  //input text
    Fun1.call(new Obj());   //对象!

window.Fun1()默認對象;Fun1.call(window)執行Fun1的對象為window; 以此類推


call函数和apply方法的第一个参数都是要传入给当前对象的对象,及函数内部的this。后面的参数都是传递给当前对象的参数。

    var func=new function(){this.a="func"}
    var myfunc=function(x){
        var a="myfunc";
        alert(this.a);  //func
        alert(x);  //var
    }
    myfunc.call(func,"var");
对于第一个参数意义都一样,但对第二个参数: apply传入的是一个参数数组,也就是将多个参数组合成为一个数组传入,而call则作为call的参数传入(从第二个参数开始)。
func.call(func1,var1,var2,var3)  ==  func.apply(func1,[var1,var2,var3])
同时使用apply的好处是可以直接将当前函数的arguments对象作为apply的第二个参数传入 区别在于 call 的第二个参数可以是任意类型,而apply的第二个参数必须是数组,也可以是arguments




apply :應用某一對象的一個方法,用另一對象替換當前對象;

apply([thisObj[,argArray]]) 

1、如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。
2、如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。

實例a

function add(a,b){alert(a+b)}function sub(a,b){alert(a-b)}add.call(sub,3,1);

這個例子其實沒什麼用,一定要找理由:不涉及到this,所以call什麼的相當於白寫;alert(4)

實例b

    function Animal(){
        this.name = "Animal";
        this.showName = function(){
            alert(this.name);
        }
    }

    function Cat(){
        this.name = "Cat";
    }

    var animal = new Animal();
    var cat = new Cat();

    //通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。
    //输入结果为"Cat"
    animal.showName.call(cat,",");
    //animal.showName.apply(cat,[]);
animal.showName.call(cat,","); 將原本的this對象指向cat,cat獲得屬性,this.name==cat.name,所以输出是Cat

實例c

 function Animal(name){    
     this.name = name;    
     this.showName = function(){    
         alert(this.name);    
     }    
 }    
   
 function Cat(name){  
     Animal.call(this, name);  
 }    
   
 var cat = new Cat("Black Cat");   
 cat.showName();
Animal.call(this, name); this為cat對象,再執行 Animal(); 裏面的this變為cat對象,所以獲得屬性與方法;最後彈出 'Black Cat'

gruntjs入門

安裝node.js,安裝gruntjs

npm install -g grunt-cli
npm install grunt --save-dev
grunt –version

1、轉到項目根文件夾下,安裝插件;

npm init

生成 package.json

{
  "name": "elmok",
  "version": "0.1.0",
  "devDependencies": {
        "grunt" : "~0.4.2",
           "grunt-contrib-concat" : "~0.3.0",
        "grunt-contrib-uglify" : "~0.3.2"
  }
}

安裝

npm install
或
npm install grunt-contrib-concat --save-dev  //按具體插件名

2、創建任務
創建Gruntfile.js

pkg: grunt.file.readJSON('package.json')引入

elmok:項目

concat:任務名;files:{新生成文件:[被合併各文件]}

concat:任務名;files:{新生成文件:[被壓縮文件]}

src:[ ] 源文件路徑

dest:[ ] 生成目標文件

banner參數,給目標文件頭部加注釋信息

<%= pkg.name %>,pkg是用grunt.file.readJSON('package.json')读取到的JSON,而且已经转换为JS对象。依照前面package.json的演示样例,这段代码会在写入文件时被替换为"my-project-name"。

JS对象和JSON来做辅助的配置 <%= grunt.template.today("yyyy-mm-dd") %> 按指定格式生成任務時間

grunt.loadNpmTasks('grunt-contrib-concat');加載任務所需插件

grunt.registerTask('default', ['concat', 'uglify']);註冊任務,任務名以數組存

module.exports = function (grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        concat: {
            elmok: {
                files: {
                    'dist/m.js': ['1.js', '2.js', '3.js', '4.js']
                }
            }
        },
        uglify: {
            elmok: {
                files: {
                    'dist/main.min.js': ['dist/main.js']
                }
            }
        }
    });
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.registerTask('default', ['concat', 'uglify']);
};

或等等類似

module.exports = function(grunt) {

    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        uglify: {
            options: {
                banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
            },
            build: {
                src: 'main.js',
                dest: 'main.min.js'
            }
        }
    });

    // Load the plugin that provides the "uglify" task.
    grunt.loadNpmTasks('grunt-contrib-uglify');

    // Default task(s).
    grunt.registerTask('default', ['uglify']);

};

最後執行:

grunt

小拓展:可任意選擇配置; 轉

options: {
    mangle: false, //不混淆变量名
    preserveComments: 'all', //不删除注释,还可以为 false(删除全部注释),some(保留@preserve @license @cc_on等注释)
    footer:'\n/*! <%= pkg.name %> 最后修改于: <%= grunt.template.today("yyyy-mm-dd") %> */'//添加footer
    report: "min"//输出压缩率,可选的值有 false(不输出信息),gzip

},
buildall: {//任务三:按原文件结构压缩js文件夹内所有JS文件
    files: [{
        expand:true,
        cwd:'js',//js目录下
        src:'**/*.js',//所有js文件
        dest: 'output/js'//输出到此目录下
    }]
},
release: {//任务四:合并压缩a.js和b.js
    files: {
        'output/js/index.min.js': ['js/a.js', 'js/main/b.js']
    }
}