js10---call方法总结

<html>
<body>
<script type="text/javascript">
function Obj(x, y){
    this.x = x ; 
    this.y = y ;
    this.say = function(){
        this.name = "aaa";//不是生成对象的属性
        gg = "gg";//不是生成对象的属性
    }
}

var o = new Obj(10,20);
alert(o.name);//undefined
alert(o.gg);//undefined

function p(){
    this.age = "age";
    alert("pppp");
}
p.call(o);//就这里一行代码o有p方法,语句执行完o就没有p方法了,属性一直还存在。
o.p();//o.p is not a function,o有p方法只有一次,上面语句执行完o就没有p方法了,属性还存在。
alert(o.age);//age,p.call(o)把函数类的属性加进对象o中


function p1(){
    this.sch = "sch";
    alert("p1");
}
o.p1();//o.p1 is not a function,不能这样加,只能通过call来动态加一次
alert(o.sch)

function Person(name,age){
    this.sch = "sch";
    alert("p1");
}
function New(f){
      var o = {};
      return function(){
          f.apply(o); //就这一行,o拥有了p方法,出了这一行就没有p方法了,但是o还是有p函数中定义的属性      
          return o;
      }
}
var new1 = New(Person)();  
new1.Person();//new1.Person is not a function,
alert(new1.sch);//sch
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/yaowen/p/6864700.html