1. //javascript 中call用处不少,用一句话概括就是动态改变this.比如说:
    2. /*------------------------------1 继承式-----------------------------*/
    3. function cat(){
    4. }
    5. //做一个原型扩展
    6. cat.prototype={
    7. food:"fish",
    8. say: function(){
    9. console.log("I love "+this.food);
    10. }
    11. }
    12. var blackCat = new cat;
    13. blackCat.say();
    14. //当我需要一条黑狗也说它喜欢什么时:
    15. blackDog = {food:"bone"};
    16. //我们不想对它重新定义say方法,那么我们可以通过call用blackCat的say方法:
    17. blackCat.say.call(blackDog);
    18. /*----------------------------2 替换式------------------------------*/
    19. function oldName() {
    20. this.oldname = function(){
    21. console.log(this.name)
    22. }
    23. }
    24. function Person(name) {
    25. this.name = null;
    26. this.Init = function (name) {
    27. this.name = name;
    28. }
    29. this.Init(name);
    30. }
    31. var oneName = new oldName();
    32. var lutong = new Person('lutong')
    33. oneName.oldname.call(lutong)
    34. /*--------------------------3 继承式----------------------------------*/
    35. function NameShowing(){
    36. this.showName = function(){
    37. console.log(this.name);
    38. }
    39. }
    40. function Person(name){
    41. this.name = null;
    42. this.Init = function(name){
    43. this.name = name;
    44. }
    45. this.Init(name);
    46. };
    47. var jeremy = new Person("Jeremy")
    48. NameShowing.call(jeremy);
    49. jeremy.showName();
    50. /*-----------------4 带有构造函数的参数 -------------------- */
    51. function Person(name, age){
    52. this.name = null;
    53. this.age = null;
    54. this.showPersonInfo = function(){
    55. console.log("Name: " + this.name + "");
    56. console.log("Age: " + this.age + "");
    57. };
    58. this.Init = function(){
    59. this.name = name;
    60. this.age = age;
    61. };
    62. this.Init();
    63. }
    64. var jeremy = new Object();
    65. Person.call(jeremy, "Jeremy", 20);
    66. jeremy.showPersonInfo();