面向对象的JavaScript-008-Function介绍
1.
// 函数
/* Declare the function 'myFunc' */
function myFunc(theObject) {
theObject.brand = "Toyota";
} /*
* Declare variable 'mycar';
* create and initialize a new Object;
* assign reference to it to 'mycar'
*/
var mycar = {
brand: "Honda",
model: "Accord",
year: 1998
}; /* Logs 'Honda' */
console.log(mycar.brand); /* Pass object reference to the function */
myFunc(mycar); /*
* Logs 'Toyota' as the value of the 'brand' property
* of the object, as changed to by the function.
*/
console.log(mycar.brand); //var y = function x() {};
//alert(x); // throws an error
//var foo = new Function("alert(anonymous);");
//foo(); //Uncaught ReferenceError: anonymous is not defined
foo(); // alerts FOO!
function foo() {
alert('FOO!');
}
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed. var x = 0; // source element
if (x == 0) { // source element
x = 10; // not a source element
function boo() {} // not a source element
}
function foo() { // source element
var y = 20; // source element
function bar() {} // source element
while (y == 10) { // source element
function blah() {} // not a source element
y++; // not a source element
}
} // function declaration
function foo() {} // function expression
(function bar() {}) // function expression
x = function hello() {} if (x) {
// function expression
function world() {}
} // function declaration
function a() {
// function declaration
function b() {}
if (0) {
// function expression
function c() {}
}
} // This function returns a string padded with leading zeros
function padZeros(num, totalLen) {
var numStr = num.toString(); // Initialize return value as string
var numZeros = totalLen - numStr.length; // Calculate no. of zeros
for (var i = 1; i <= numZeros; i++) {
numStr = "0" + numStr;
}
return numStr;
}
var result;
result = padZeros(42,4); // returns "0042"
console.log(result);
result = padZeros(42,2); // returns "42"
console.log(result);
result = padZeros(5,4); // returns "0005"
console.log(result); // 菲波那其数
var factorial = function fac(n) { return n<2 ? 1 : n*fac(n-1) };
console.log(factorial(3)); function map(f,a) {
var result = [], // Create a new Array
i;
for (i = 0; i != a.length; i++)
result[i] = f(a[i]);
return result;
}
console.log(map(function(x) {return x * x * x}, [0, 1, 2, 5, 10])); // returns [0, 1, 8, 125, 1000]. // 阶乘
function factorial(n){
if ((n === 0) || (n === 1))
return 1;
else
return (n * factorial(n - 1));
}
var a, b, c, d, e;
a = factorial(1); // a gets the value 1
b = factorial(2); // b gets the value 2
c = factorial(3); // c gets the value 6
d = factorial(4); // d gets the value 24
e = factorial(5); // e gets the value 120
console.log(a);
console.log(b);
console.log(c);
console.log(d);
console.log(e); // Function scope
// The following variables are defined in the global scope
var num1 = 20,
num2 = 3,
name = "Chamahk"; // This function is defined in the global scope
function multiply() {
return num1 * num2;
} multiply(); // Returns 60 // A nested function example
function getScore () {
var num1 = 2,
num2 = 3; function add() {
return name + " scored " + (num1 + num2);
} return add();
} console.log(getScore()); // Returns "Chamahk scored 5" var x = 0;
while (x < 10) { // "x < 10" is the loop condition
// do stuff
x++;
} // can be converted into a recursive function and a call to that function:
function loop(x) {
if (x >= 10) // "x >= 10" is the exit condition (equivalent to "!(x < 10)")
return;
// do stuff
loop(x + 1); // the recursive call
}
loop(0); // However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (e.g. the DOM) is more easily done using recursion:
function walkTree(node) {
if (node == null) //
return;
// do something with node
for (var i = 0; i < node.childNodes.length; i++) {
walkTree(node.childNodes[i]);
}
} // function foo(i) {
// if (i < 0)
// return;
// console.log('begin:' + i);
// foo(i - 1);
// console.log('end:' + i);
// }
//foo(3);
// Output: // begin:3
// begin:2
// begin:1
// begin:0
// end:0
// end:1
// end:2
// end:3 // Nested functions and closures
function addSquares(a,b) {
function square(x) {
return x * x;
}
return square(a) + square(b);
}
a = addSquares(2,3); // returns 13
b = addSquares(3,4); // returns 25
c = addSquares(4,5); // returns 41 // Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function: function outside(x) {
function inside(y) {
return x + y;
}
return inside;
}
fn_inside = outside(3); // Think of it like: give me a function that adds 3 to whatever you give it
result = fn_inside(5); // returns 8 result1 = outside(3)(5); // returns 8 // Multiply-nested functions
function A(x) {
function B(y) {
function C(z) {
console.log(x + y + z);
}
C(3);
}
B(2);
}
A(1); // logs 6 (1 + 2 + 3) // Name conflicts
function outside() {
var x = 10;
function inside(x) {
return x;
}
return inside;
}
result = outside()(20); // returns 20 instead of 10 // Closures
var pet = function(name) { // The outer function defines a variable called "name"
var getName = function() {
return name; // The inner function has access to the "name" variable of the outer function
}
return getName; // Return the inner function, thereby exposing it to outer scopes
},
myPet = pet("Vivie"); myPet(); // Returns "Vivie" var createPet = function(name) {
var sex; return {
setName: function(newName) {
name = newName;
}, getName: function() {
return name;
}, getSex: function() {
return sex;
}, setSex: function(newSex) {
if(typeof newSex === "string" && (newSex.toLowerCase() === "male" || newSex.toLowerCase() === "female")) {
sex = newSex;
}
}
}
} var pet = createPet("Vivie");
pet.getName(); // Vivie pet.setName("Oliver");
pet.setSex("male");
pet.getSex(); // male
pet.getName(); // Oliver var getCode = (function(){
var secureCode = "0]Eal(eh&2"; // A code we do not want outsiders to be able to modify... return function () {
return secureCode;
};
})(); getCode(); // Returns the secureCode var createPet = function(name) { // Outer function defines a variable called "name"
return {
setName: function(name) { // Enclosed function also defines a variable called "name"
name = name; // ??? How do we access the "name" defined by the outer function ???
}
}
} // Using the arguments object
function myConcat(separator) {
var result = "", // initialize list
i;
// iterate through arguments
for (i = 1; i < arguments.length; i++) {
result += arguments[i] + separator;
}
return result;
} // returns "red, orange, blue, "
myConcat(", ", "red", "orange", "blue"); // returns "elephant; giraffe; lion; cheetah; "
myConcat("; ", "elephant", "giraffe", "lion", "cheetah"); // returns "sage. basil. oregano. pepper. parsley. "
myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley"); // Default parameters
function multiply(a, b) {
b = typeof b !== 'undefined' ? b : 1; return a*b;
} multiply(5); // // function multiply2(a, b = 1) {
// return a*b;
// } // multiply2(5); // 5 // Rest parameters
// function multiply(multiplier, ...theArgs) {
// return theArgs.map(x => multiplier * x);
// } // var arr = multiply(2, 1, 2, 3);
// console.log(arr); // [2, 4, 6] // Arrow functions
var a = [
"Hydrogen",
"Helium",
"Lithium",
"Beryllium"
]; var a2 = a.map(function(s){ return s.length }); // var a3 = a.map( s => s.length ); // Lexical this function Person() {
// The Person() constructor defines `this` as itself.
this.age = 0; setInterval(function growUp() {
// In nonstrict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
} var p = new Person(); function Person() {
var self = this; // Some choose `that` instead of `self`.
// Choose one and be consistent.
self.age = 0; setInterval(function growUp() {
// The callback refers to the `self` variable of which
// the value is the expected object.
self.age++;
}, 1000);
} // function Person(){
// this.age = 0; // setInterval(() => {
// this.age++; // |this| properly refers to the person object
// }, 1000);
// } // var p = new Person();
面向对象的JavaScript-008-Function介绍的更多相关文章
- 摘抄--全面理解面向对象的 JavaScript
全面理解面向对象的 JavaScript JavaScript 函数式脚本语言特性以及其看似随意的编写风格,导致长期以来人们对这一门语言的误解,即认为 JavaScript 不是一门面向对象的语言,或 ...
- 深入全面理解面向对象的 JavaScript
深入全面理解面向对象的 JavaScript (原著: 曾 滢, 软件工程师, IBM,2013 年 4 月 17 日) JavaScript 函数式脚本语言特性以及其看似随意的编写风格,导致长期以来 ...
- 万字长文深度剖析面向对象的javascript
目录 简介 什么是对象 构造函数 构造函数的特点 new命令的原理 prototype对象 Object的prototype操作 Object.getPrototypeOf Object.setPro ...
- 前端开发:面向对象与javascript中的面向对象实现(二)构造函数与原型
前端开发:面向对象与javascript中的面向对象实现(二)构造函数与原型 前言(题外话): 有人说拖延症是一个绝症,哎呀治不好了.先不说这是一个每个人都多多少少会有的,也不管它究竟对生活有多么大的 ...
- 前端开发:面向对象与javascript中的面向对象实现(一)
前端开发:面向对象与javascript中的面向对象实现(一) 前言: 人生在世,这找不到对象是万万不行的.咱们生活中,找不到对象要挨骂,代码里也一样.朋友问我说:“嘿,在干嘛呢......”,我:“ ...
- 面向对象的 JavaScript
面向对象的javascript 一.创建对象 创建对象的几种方式: var obj = {}; var obj = new Object(); var obj = Object.create(fath ...
- JavaScript之Function函数深入总结
整理了JavaScript中函数Function的各种,感觉函数就是一大对象啊,各种知识点都能牵扯进来,不单单是 Function 这个本身原生的引用类型的各种用法,还包含执行环境,作用域,闭包,上下 ...
- JavaScript Date对象介绍
原文:JavaScript Date对象介绍 Date 日期和时间对象 1. 介绍 Date对象,是操作日期和时间的对象.Date对象对日期和时间的操作只能通过方法. 2. 构造函数 2.1 new ...
- javascript 之Function对象的apply(),call(),bind(),方法和arguments,caller,length属性
注:这篇文章原文:http://www.jb51.net/article/30883.htm 自己作为学习,重新写写. 一.写在前面的话 前端javascript编程还只是略懂皮毛,DOM知道一点,j ...
- 面向对象的JavaScript --- 动态类型语言
面向对象的JavaScript --- 动态类型语言 动态类型语言与面向接口编程 JavaScript 没有提供传统面向对象语言中的类式继承,而是通过原型委托的方式来实现对象与对象之间的继承. Jav ...
随机推荐
- shell中date命令对month进行加减操作的bug
shell脚本中如何取上个月的月份呢?很容易能想到下面的命令: date +%Y%m -d '-1 month' 或者 date +%Y%m -d 'last month' 在大部分情况下这个命令 ...
- linux下进程cpu占用过高问题定位方法
背景 记得前段时间,同事说他们测试环境的服务器cpu使用率一直处于100%,本地又没有什么接口调用,为什么会这样?cpu使用率居高不下,自然是有某些线程一直占用着cpu资源,那又如何查看占用cpu较高 ...
- 模拟admin组件自己开发stark组件之创建篇
admin组件 admin组件为我们提供了针对django管理页面 我们先简短来看下django的admin组件的启动流程,注册流程,url匹配过程 启动注册 1. 扫描所有应用下的注册了应用中的ad ...
- 【做题记录】USACO gold * 50(第一篇)
orz xhk 5/50 1597: [Usaco2008 Mar]土地购买 $ f[i]=min(f[j]+x[i]*y[j+1]) $ 然后斜率优化 1699: [Usaco2007 Jan]Ba ...
- ceph中用sgdisk工具进行分区--------固定uuid
ceph中两种类型分区的type code: type type code journal 45b0969e-9b03-4f30-b4c6-b4b80ceff106 osd 4fbd7e29-9d25 ...
- 编码转换(UTF8->GBK)
WCHAR woutstr[]; ]; , value, -, NULL, ); MultiByteToWideChar(CP_UTF8, , value, -, woutstr, len); len ...
- jquery 实现点击图片居住放大缩小
该功能是基于jquery实现的,所以 第一步则是引入jquery jquery下载地址:https://jquery.com/download/ 或者使用此时调试的版本(3版本) /*! jQuery ...
- 版本控制git之一 - 仓库管理
git 再开始这个话题之前,让我想起了一件很痛苦的事情,在我大学写毕业论文的时候,我当时的文件是这样保存的 毕业论文_初稿.doc 毕业论文_修改1.doc 毕业论文_修改2.doc 毕业论文_修改3 ...
- ListBox和ComboBox绑定数据简单例子
1. 将集合数据绑定到ListBox和ComboBox控件,界面上显示某个属性的内容 //自定义了Person类(有Name,Age,Heigth等属性) List<Person> per ...
- mongodb(三)
索引详讲索引管理空间索引 for(var i = 0 ; i<200000 ;i++){ db.books.insert({number:i,name:i+"book"}) ...