日期:2014-05-16  浏览次数:20425 次

js基础的问题请教?

window.onload = function() {

  function Base() {
    this.elements = [];
  }

  Base.prototype.getId = function(id) {
    this.elements.push(document.getElementById('a'));
    alert(this);  //这行的this
  };
  Base.getId('a');
};


错误提示是:TypeError: Base.getId is not a function
为什么啊?
请问this指的是Base对象还是Base的原型对象Base.prototype呢?
谢谢!

------解决方案--------------------

window.onload = function() {
 
  function Base() {
    this.elements = [];
  }
 
  Base.prototype.getId = function(id) {
    this.elements.push(document.getElementById('a'));
    alert(this);  //这行的this
  };

  var base = new Base();
  base.getId('a');
};


要new!
------解决方案--------------------
base的对象
------解决方案--------------------
Base本身是个对象
可以用for(var i in Base){
     alert(Base[i]+" "+i);
}
或者JSON.stringify(Base)
查看Base这个对象的属性
new Base();产生新的对象 获得Base.prototype原型链上的属性
------解决方案--------------------
楼主不够细心啊~~对象根本没有创建啊。
至于this,是永远指向当前运行的环境的。
function test() {
    console.log(this.x);
}
var o = {};
o.x = 1;
o.m = test;
o.m();
test();

运行一下就大概理解了。