JS 类方法调用

JavaScript012

JS 类方法调用,第1张

window.alert(p.getName1()+"\n" + People.getName2() + "\n" + p.getName3())

这里先执行括号里所有的内容,再执行最外层的window.alert,

所以读到 People.getName2()  时,函数内的alert就先弹出来了,

因为getName2只有一个alert方法,this.nameObject自带的方法,会返回当前对象的全名,

所以弹出显示People,

构造函数People里虽然有this.name,但是构造函数没实例化是无法调用内部的属性,

所以People.getName2() 返回的是undefined,

js中的类通过function进行定义,使用时,直接new 函数名就是一个类定义。

举例

function TestClass(){

   this.a='2'

   this.kk = function show(){

     alert('3')

   }

}

var tc = new TestClass()//实例化class

alert(tc.a)//访问class的属性

alert(tc.kk())//访问方法

你的代码可以通过如下

var tc = new a()

tc.c('测试')

function fun(){

var _this = this

//如果函数是用var定义的私有函数,如下

var func1 = function(){ }

//那么类中其他函数都可以直接通过func1()的形式调用

//如果函数是共有的,即用this定义,如下

this.func2 = function(){ }

/*则需要得到func对像的引用,即fun中的this(注意:是fun中的).

然而到了调用者函数(如下的caller)内部时,this指的是caller函数而不再是fun,所以可以考虑在fun中定义一个私有变量 var _this = this 来保证指向的是fun

*/

//例子:在this.caller中调用类中的其他函数

this.caller = function(){

func1()//私有函数直接调用

_this.func2()//公共函数,需要fun的this的指向

}

}