js怎么调用function中的function

JavaScript010

js怎么调用function中的function,第1张

// 1, 方法调用模式 <br>// 当一个函数被保存为对象的一个属性时,我们称之它为该对象的一个方法,那么this被绑定到该对象上 <br>var myObject={ <br>name : "myObject" , <br>value : 0 , <br>increment : function(num){ <br>this.value += typeof(num) === 'number' ? num : 0<br>return this<br>} , <br>toString : function(){ <br>return '[Object:' + this.name + ' {value:' + this.value + '}]'<br>} <br>} <br>alert(myObject.increment(10).increment(20).toString())// [Object:myObject {value:30}] <br><br>// 2, 函数调用模式 <br>// 当一个函数并非一个对象的函数时,那么它被当作一个函数来调用,this被绑定到全局对象上。这是语言设计的一个错误。倘若语言设计正确,当内部函数调用时,this应该仍然绑定到外部函数的this变量上 <br>var myObject={ <br>name : "myObject" , <br>value : 0 , <br>increment : function(num){ <br>this.value += typeof(num) === 'number' ? num : 0<br>return this<br>} , <br>toString : function(){ <br>return '[Object:' + this.name + ' {value:' + this.value + '}]'<br>}, <br>getInfo: function(){ <br>var self=this<br>return (function(){ <br>//return this.toString()// 内部匿名函数中this指向了全局对象window, 输出 [object Window] <br>return self.toString()// 定义一个变量selft并给它赋值为this,那么内部函数通过该变量访问到指向该对象的this <br>})()<br>} <br>} <br>alert(myObject.increment(10).increment(20).toString())// [Object:myObject {value:30}] <br><br>// 3, 构造器调用模式 <br>// JavaScript是一门基于原型继承的语言, 这意味着对象可以直接从其他对象继承属性, 该语言是无类别的。 <br>// 如果一个函数前面带上new来调用,那么将创建一个隐藏连接到该函数的prototype成员的新对象,同时this将会被绑定到构造函数的实例上。 <br>function MyObject(name){ <br>this.name = name || 'MyObject'<br>this.value=0<br>this.increment = function(num){ <br>this.value += typeof(num) === 'number' ? num : 0<br>}<br>this.toString = function(){ <br>return '[Object:' + this.name + ' {value:' + this.value + '}]'<br>} <br>this.target = this<br>}

Js文件中调用其它Js函数的方法:

1、例如有这样一个html,里面有一个按钮,当按下时调用b.js文件中的方法b()。而b()中又要调用a.js文件中的方法a()。那我们应该怎么做呢?

首先,在html中引入b.js,并在之后加入引用语句。必须注意,将要引入的Js文件代码放在下面。

b.js文件中引入a.js,内容如下:

new_element=document.createElement("script")

new_element.setAttribute("type","text/javascript")

new_element.setAttribute("src","a.js")// 在这里引入了a.js

document.body.appendChild(new_element)

function b() {

a()

}

在b.js文件中前4行代码中我们引入了a.js文件,并在第7行代码中调用了a.js代码中的a()方法。

注意:一定要放在body下面。

因为在b.js中用到了body(document.body.appendChild(new_element))

如果将引如b.js的代码放在body上面,也就是说, 进入页面后,还没有生成body就已经执行b.js里的document.body.appendChild(new_element)了。 这时body不存在就会抛javascript错误。