面向对象的JavaScript-005-Function.prototype.call()的3种作用
2016-05-24 15:13
645 查看
1.
// call的3种作用 // 1.Using call to chain constructors for an object function Product(name, price) { this.name = name; this.price = price; if (price < 0) { throw RangeError('Cannot create product ' + this.name + ' with a negative price'); } } function Food(name, price) { Product.call(this, name, price); this.category = 'food'; } function Toy(name, price) { Product.call(this, name, price); this.category = 'toy'; } var cheese = new Food('feta', 5); console.log(cheese); var fun = new Toy('robot', 40); console.log(fun); // 2.Using call to invoke an anonymous function var animals = [ { species: 'Lion', name: 'King' }, { species: 'Whale', name: 'Fail' } ]; for (var i = 0; i < animals.length; i++) { (function(i) { this.print = function() { console.log('#' + i + ' ' + this.species + ': ' + this.name); } this.print(); }).call(animals[i], i); } // Using call to invoke a function and specifying the context for 'this' // In below example, when we will call greet the value of this will be bind to object i. function greet() { var reply = [this.person, 'Is An Awesome', this.role].join(' '); console.log(reply); } var i = { person: 'Douglas Crockford', role: 'Javascript Developer' }; greet.call(i); // Douglas Crockford Is An Awesome Javascript Developer
相关文章推荐
- js继承,各种继承的优缺点(原型链继承,组合继承,寄生组合继承)
- JS 清除字符串数组中,重复元素的实现方法
- JS正则表达式
- 原生js dom操作
- autocomplete+ajax+json实现自动补全功能
- 接口json转化为datatable
- 原生js的数组除重复简单实例
- json传值以及ajax接收详解
- 面向对象的JavaScript-004
- javascript策略模式
- JS获取屏幕高度的简单实现代码
- 按钮定时开关
- 面向对象的JavaScript-003
- javascript之BOM浏览器对象模型引入
- javascript之BOM浏览器对象模型引入
- go提交json、获取json、解析json
- 使用js几秒钟后跳转到对应的页面
- javascript之prototype原型属性案例
- javascript之prototype原型属性案例
- JS this