我创建一个类var Emp = function() { };
,然后在该类的原型中将函数定义为
Emp.prototype.function1 = function() { /* some definition */ };
Emp.prototype.function2 = function() { /* some definition */ };
// .. so on
对性能有什么影响?哪种方法有效?为什么?
情况1:如果我调用函数
Emp.prototype.function1();
情况2:如果我先创建一个Emp
实例
var empobj = new Emp();
empobj.function1(); // function calling
如果使用情况1,则默认情况this
下上下文将指向prototype
对象,因此instance
无法使用该值访问值。
例如:
var x = function(){ this.a = 10 };
x.prototype.y = function(){ console.log(this.a) };
x.prototype.y(); // This will print undefined since
//there is no properties other than y in the prototype of x.
在第2种情况下,您可以同时访问prototype
对象和instances
值。一个示例代码是
var x = function(){ this.a = 10 };
x.prototype.y = function(){ console.log(this.a) };
var obj = new x();
obj.y(); // `y` can be accessed also. And it will output 10.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句