简体   繁体   English

javascript访问新创建的对象

[英]javascript accessing newly created object

If 如果

function foos(){alert(this)}
x=new foos() which is==={foo();}//as this keyword points to Object object

so than i can say foos as the method of that new object but when i do this 所以我可以说foos作为该新对象的方法,但是当我这样做时

x.foos();//after the object is initialized,it dont work at all why?

The code creates an instance of foos on which foos is not defined as a property on that object. 该代码创建一个foos实例,在该实例上foos未被定义为该对象的属性。

If you want to add a property on an object try something like: 如果要在对象上添加属性,请尝试以下操作:

function foos(){
  this.myProp = "Hello";
}

var x = new foos();

alert(x.myProp);

If you want to add a method to an object use: 如果要向对象添加方法,请使用:

foos.prototype.myFunc = function(){
  alert(this.myProp);
};

x.myFunc(); //alerts Hello

'foos' is the constructor function and it will not be part of the newly object methods, if u want to add methods u can use it like this: 'foos'是构造函数,它不会成为新对象方法的一部分,如果您想添加方法,可以这样使用它:

function MyClass() { }

MyClass.prototype.foos = function () {
    alert(this);
}

and then: 接着:

var x = new MyClass();
x.foos();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM